c++ - 如何在 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 太累了,这当然是我的情况。请帮忙
解决方案
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");
}
推荐阅读
- c# - HTML 敏捷性 - 在下面的代码中仅找到一条记录
- google-sheets - 我正在尝试从一张到另一张的谷歌表格中获取数据,并在新表格上操作接收到的数据
- php - 如何从外部 URL 重写/重构 JSON?
- java - SPeL 将字符串转换为整数
- android - 如何为整个 Cordova 应用程序添加一个恢复事件?
- javascript - 使用 beforeAll 而不是 beforeEach 优化测试开玩笑
- spring-boot - 基于比特桶推送Java代码触发的GCP Cloud Build
- mysql - 如何使用 sequelize.js 从关联模型中加载属性
- excel - 使用 VBA 与 IE 下拉菜单交互。(发送密钥不起作用)(getElementbytag 不起作用)
- javascript - Javascript无法使用window.postMessage向弹出窗口发送消息