如何解决如何在C++ linux中将系统调用转换为fork
这是用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 太费力了,这当然是我的情况。 请帮忙
解决方法
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");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。