【问题标题】:How to convert the system call to fork in C++ linux如何在 C++ linux 中将系统调用转换为 fork
【发布时间】:2021-09-05 18:41:48
【问题描述】:

这是在C++ linux代码中播放声音文件的代码

 string str1 = "aplay ";
 str1 = str1 + " out.wav" + " & ";
 const char *command = str1.c_str();
 system(command);

** 完整代码在这里:Playing sound C++ linux aplay : device or resource busy

我只是想知道如何在 fork() 中播放这个,因为我读到系统调用对 cpu 的负担太大,这当然是我的情况。 请帮忙

【问题讨论】:

  • 欢迎使用 Stackoverflow!请为您提供的代码添加 minimal reproducible example
  • 我不认为fork 会比system 快很多,主要成本是启动一个新进程
  • systemforkexec 的组合。它不是“对 CPU 负担过重”,但它确实会阻塞,直到程序完成。
  • 您需要做的是避免每秒播放 30 个声音文件。无论您如何启动aplay,这都会成为一个问题。寻找一些用于播放声音的库,而不是委托给单独的进程。

标签: c++ linux fork


【解决方案1】:

fork 将复制您的流程,以便您轻松编写:

// fork the current process: beyond this point, you will have 2 process
int ret = fork();
if (ret == 0) {
   // in child: execute the long command
   system("aplay out.wav");
   // exit the child process
   exit(0);
}

// child process will not go here

if (ret < 0) {
    perror("fork");
}

之后,您应该知道system 会为您服务fork + exec + wait。既然你不希望你的父进程等待子进程,你可以这样写:

// fork the current process: beyond this point, you will have 2 process
int ret = fork();
if (ret == 0) {
   // in child: execute the long command
   char program[] = "/usr/bin/aplay";
   char *args[] = {"/usr/bin/aplay", "out.wav" };
   ret = execv(program, args); 

  // this point will be reach only if `exec` fails
  // so if we reach this point, we've got an error.
  perror("execv");

  exit(0);
}

// child process will not go here

if (ret < 0) {
    perror("fork");
}

【讨论】:

  • 现在是双叉。你首先 fork 一个子进程,然后 fork aplay。做两次工作根本不是 CPU 优化!你可以打电话给execl 而不是system。这与最初的 system 调用一样有效,因此它仍然无法回答问题,但它也更冗长且容易失败。
猜你喜欢
  • 1970-01-01
  • 2015-12-22
  • 2012-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多