Note that there are some explanatory texts on larger screens.

plurals
  1. POReading from a pipe to my child process
    text
    copied!<p>Hopefully a simple question. I'm trying to learn, simultaneously, fork(), pipe(), and waitpid() and running into some problems.</p> <pre><code>if (pipe(myout)&lt;0 || pipe(myin)&lt;0 || pipe(myerr)&lt;0) { perror("Couldn't make pipes"); return; } int childpid=fork(); if (childpid==0) { //child fdopen(myout[1], "w"); fdopen(myin[1], "r"); fdopen(myerr[1], "w"); dup2(myout[1], 1); dup2(myin[1], 0); dup2(myerr[1], 2); printf("This should be seen\n"); fclose(stdout); fclose(stdin); fclose(stderr); sleep(10); _exit(0); } else { //parent, wait on child printf("parent, monitoring\n"); sim_out=fdopen(myout[0], "r"); sim_in=fdopen(myin[0], "w"); sim_err=fdopen(myerr[0], "r"); printf("have my fds\n"); int status; do { int ch; if (read(myout[0], &amp;ch, 1)&gt;0) write(1, &amp;ch, 1); else printf("no go\n"); waitpid(childpid, &amp;status, WNOHANG); } while (!WIFEXITED(status) &amp;&amp; !WIFSIGNALED(status)); } </code></pre> <p>I'm getting:</p> <blockquote> <p>parent, monitoring have my fds T</p> </blockquote> <p>before the program exits - that is, the loop runs only once. I have a check below that, and it's coming up WIFEXITED() so the process is supposed to have exited normally. But what bothers me is that there's a sleep(10) before that happens, and this happens immediately - not to mention that the child processes are left running for the remaining wait time.</p> <p>I'm fundamentally misunderstanding something, clearly. My expectation was that the parent loop would block until it sees a character from the child, read it, then check to see if it was still alive. I certainly didn't expect waitpid() to set WIFEXITED when the child was still alive.</p> <p>Where am I wrong?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload