So I was trying to run a system command (or exec, or whatever) at a child process after a fork(), and push some input to it, and then get its output. It looks like this after the fork(), and pc and cp is parent-child and child-parent pipes.
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);
Now, it seems to work nicely (if you want the code : http://pastebin.com/Fh7GrxYm ), but when I was talking at #posix on irc, they were going mad, about how this can potentially block, and how it "depends on how the kernel is feeling".
There was an msdn blog post about the same thing: http://blogs.msdn.com/b/oldnewthing/archive/2011/07/07/10183884.aspx
How can one prevent blocking, if any, etc?