void doWork(){
int fd[2];
int pret = pipe(fd);
close(0);
close(1);
int dret = dup2(fd[1], 1);
close(fd[1]);
while(1){
char buf[256];
system("whoami");
int rret = read(fd[0], buf, 256);
if(/* something interesting */){
return;
}
}
}
int main(int argc, char* argv[]){
int children = 2;
for(unsigned work = 0; work < children; ++work){
pid_t pid = fork();
if(pid == 0){
doWork();
break;
}
}
int status;
wait(&status);
return 0;
}
这个例子有什么问题?我试图让每个子进程调用一个外部程序,然后从管道中读取该程序的输出。我的代码仅在 children 设置为 1 时有效。
编辑:我正在尝试使用 fork/pipes 实现任务并行。父进程和子进程之间没有通信。每个子进程执行一个外部程序,读取输出,处理输出,并继续直到找到所需的输出。
最佳答案
您需要在 fork()
之前创建管道,而不是之后。在您的代码中,只有子进程才会有管道。您需要两个进程来共享它。
例如:
int fd[2];
pid_t pid;
if (pipe(fd)) { /* TODO: handle error */ }
pid = fork();
if (pid < 0) { /* TODO: handle error */ }
if (pid == 0)
{
/* We are the child. Set fd[1] as stdout. */
if (dup2(fd[1], 1)) { /* TODO: handle error */ }
/* Close fd[0]; this process doesn't need it. */
close(fd[0]);
do_work();
exit(0);
}
else
{
/* We are the parent... */
/* Close the other guy's write fd. */
close(fd[1]);
/* Now read from fd[0] */
/* Possibly waitpid() on child pid, etc. */
}
此外:我喜欢在 fork()
之前调用 fflush(stdout);
。否则您将观察到 printf()
的奇怪行为。
关于c++ - 平行叉管,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4898294/