【发布时间】:2012-09-20 15:31:51
【问题描述】:
在下面的代码中,一个进程创建了一个子进程 (fork()),然后该子进程通过调用 exec() 替换自己。 exec 的 stdout 写在 pipe 而不是 shell 中。然后父进程从管道中读取 exec 用 while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
写入的内容有人能告诉我如何做与上述完全相同的事情,但有 N 个子进程(它们用上面的 exec 替换自己)。
int pipefd[2];
pipe(pipefd);
if (fork() == 0)
{
close(pipefd[0]); // close reading end in the child
dup2(pipefd[1], 1); // send stdout to the pipe
dup2(pipefd[1], 2); // send stderr to the pipe
close(pipefd[1]); // this descriptor is no longer needed
exec(...);
}
else
{
// parent
char buffer[1024];
close(pipefd[1]); // close the write end of the pipe in the parent
while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
{
}
}
【问题讨论】:
-
我没有时间输入完整的答案,但
select()是您正在寻找的功能——它会同时等待 N 个文件句柄并为您提供“准备好”文件句柄(“准备好”的意思是“不会在读取时阻塞或已在另一端关闭”)。 -
孩子们需要同时写作吗?
-
是的,他们需要同时写