首页 > 解决方案 > 如何在 C++ linux 中将系统调用转换为 fork

问题描述

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

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

** 此处提供完整代码:播放声音 C++ linux aplay:设备或资源忙

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

标签: c++linuxfork

解决方案


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++ 。由于您不希望您的父进程等待孩子,您可以编写:execwait

// 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");
}

推荐阅读