在正确的时间关闭并在 C 中等待过程



我有一个创建两个子进程的函数。在第一个子进程中,我正在写入一个文件,在第二个子进程中,我也在与第一个不同的文件中写入。 在爸爸的过程中,我正在执行函数execvp

我需要的是函数execvpstdoutstderr,以便两个子进程可以在文件中写入从stderrstdout传出的内容。最后,我将合并两个文件。

我想知道我应该在哪里关闭管道以及在哪里使用 wait 这样我就不会在使用函数readwrite时遇到问题,这样我就不会进入无限循环。我没有实现创建文件的函数、合并文件的函数和运行 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可以简单地添加额外的管道。

最新更新