【发布时间】:2011-07-08 05:57:36
【问题描述】:
所以我试图在 fork() 之后在子进程中运行系统命令(或 exec 或其他),并将一些输入推送给它,然后获取它的输出。在fork()之后是这样的,pc和cp是父子管道和子父管道。
case 0:
/* Child. */
close(STDOUT_FILENO); /* Close current stdout. */
dup2(cp[1], STDOUT_FILENO);
close(STDIN_FILENO);
dup2(pc[0], STDIN_FILENO);
close( pc[1]);
close( cp[0]);
execlp("cat", "cat", NULL);
exit(1);
default:
/* Parent. */
/* Close what we don't need. */
printf("Input to child:\n");
string theinput("Hey there baby");
write(pc[1], theinput.c_str(), theinput.size());
close(pc[1]);
cout << "The input : " << theinput << endl;
printf("\nOutput from child:\n");
close(cp[1]);
while( read(cp[0], &ch, 1) == 1)
{
write(1, &ch, 1);
outcount++;
}
exit(0);
现在,它似乎工作得很好(如果你想要代码:http://pastebin.com/Fh7GrxYm),但是当我在 irc 上的 #posix 上讲话时,他们疯了,关于这可能如何阻止,以及它如何“取决于关于内核的感受”。
有一篇关于同一件事的 msdn 博客文章:http://blogs.msdn.com/b/oldnewthing/archive/2011/07/07/10183884.aspx
如何防止阻塞(如果有的话)等?
【问题讨论】:
标签: posix fork pipe interprocess