c - 在正确的时间关闭并在 C 中等待过程
问题描述
我有一个创建两个子进程的函数。在第一个子进程中,我正在写入一个文件,而在第二个子进程中,我也在一个与第一个不同的文件中写入。在爸爸进程中,我正在执行该功能execvp
。
我需要的是函数的stdout
and ,以便两个子进程可以在文件中写入从and发出的内容。然后最后我合并这两个文件。stderr
execvp
stderr
stdout
我想知道我应该在哪里关闭管道以及我应该在哪里使用等待,这样我就不会在使用函数时遇到问题read
,write
并且这样我就不会陷入无限循环。我没有实现创建文件的函数、合并文件的函数和运行 shell 指令的函数,因为我只是想知道这是否是该函数的最佳结构createTwoChild.
解决方案
与评论一致,我在这里提供了一个骨架(仅针对标准输出进行了简化):
if (pipe(fd)<0) goto my_sys_error; // just an example to get out of here
if ((pid_child=fork())<0) {
close(fd[0]); close(fd[1]);
goto my_sys_error; // you can also use something like e.g. "return -1" to handle the error
}
if (!pid_child) {
// the child process with exec() of which we want to get the output
close(fd[0]); close(0);
dup2(fd[1],1); close(fd[1]);
execXX(...); // some of exec() family also spawn a shell here
close(1);
_exit(127); // This must not happen
}
// master/parent
close(fd[1]); // master doesn't need, only child writes to it
i = read(fd[0],p,PIPEBUF_SIZE);
if (i>0) {
// usual handling, write to file, do whatever you like
// should be while() instead of if(), just simplified
} else {
// handle it, e.g. print "no data from extcmd"
}
close(fd[0]); // close the last fd
waitpid(pid_child, &status_child, 0);
if (!WIFEXITED(status_child)) {
kill(pid_child,SIGKILL);
}
一些注意事项:
- 这实际上是
popen()
. - 当孩子退出时,您将在读取时获得 EOF - 这种简单的方式不需要 SIGCHLD 的 sighandler。
- 未涵盖的其他信号处理。
- stderr 可以简单地添加一个额外的管道。
推荐阅读
- .net - 为什么服务器上收到的 gRPC 截止日期与客户端发送的截止日期不同
- javascript - p5画布覆盖的元素
- javascript - 如何根据 Firestore 中的子集合文档值返回父集合?
- android - git checkout 从一个分支到另一个分支删除了所有本地更改。我怎样才能找回它们?
- flutter - Flutter Firebase 电话身份验证未发送短信代码。直接调用 PhoneCodeAutoRetrievalTimeout 方法。这是我的代码
- apache-spark - python作业上的Spark提交过程泄漏
- ios - 复杂视图的iOS测试自动化,UIAccessabilityContainer?
- python - 我如何让程序每次打印不同的响应?
- c# - c# DateTime.Parse 精度问题
- python - 如何使用 `array('f')` 类似的语法定义二维数组