Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think I can see several issues. I'll try to mention them in order of appearance.</p> <ul> <li>You should check <code>fork</code> for the return value <code>-1</code> which indicates an error (no child will have been forked in this case).</li> <li>All your calls to <code>fdopen</code> leak resources (depending on the implementation; the one on RHEL4 leaks). They return a <code>FILE*</code> which you could then use in <code>fwrite</code> etc. and then close by doing <code>fclose</code> on them. But you throw that value away. You don't need to open the pipe for reading/writing. Pipes are suitable for that when created.</li> <li>The child should close the ends of the pipe it does not use. Add <code>close (myin [1]); myin [1] = -1; close (myout [0]); myout [0] = -1; close (myerr [0]); myerr [0] = -1;</code></li> <li>The <code>dup2</code> are technically fine on all Linux variants I know, but it is customary to use the first fd of a pipe for reading and the other for writing. Thus, your <code>dup2</code>s would be best changed to <code>dup2 (myin [0], STDIN_FILENO); dup2 (myout [1], STDOUT_FILENO); dup2 (myerr [1], STDERR_FILENO);</code></li> <li>The parent should close the ends of the pipe it does not use. Add <code>close (myin [0]); myin [0] = -1; close (myout [1]); myout [1] = -1; close (myerr [1]); myerr [1] = -1;</code></li> <li><strong>Your main problem:</strong> You check the possibly uninitialized <code>status</code> for your child's exit code. But <code>waitpid</code> has not yet been called. You should check <code>waitpid</code>'s exit code and not evaluate <code>status</code> if it returns something other than <code>childpid</code>.</li> </ul> <h2>Edit</h2> <p>Since only the pipe ends that you actually need are open now, the operating system will detect a broken pipe for you. The pipe breaks when the child does <code>fclose (stdout)</code>. The parent can still proceed to read all the data that may be in the pipe, but after that <code>read</code> will return zero, indicating a broken pipe.</p> <p>Thus, you can actually spare the call to <code>waitpid</code>. You could instead simply wait for <code>read</code> to return zero. This is not 100% equivalent, though, since your child closes its end of the pipe before it goes to <code>sleep</code> (causing the parent to proceed when all data have been read), whereas the <code>waitpid</code> version, of course, only proceeds when the child actually died.</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