Search code examples
cmacospopen

waiting for popen subprocess to terminate before reading


How can I tell when the process started by popen is done?

I'm passing the descriptor (from fileno() called on the FILE * returned by popen) to a function which calls fstat() and uses the value to returned to determine how much to read. Surprisingly this actually works if there is a delay (for instance, stepping through the debugger) but returns a file size of zero if called immediately after the popen. So I need some way to wait until all the output is ready - how can I do this? I assume I can't call pclose() even though it does this waiting, because then the descriptor isn't valid any more.

Update: Actually, it appears the code works fine if I pretend the fstat() failed on the pipe call - the issue seems to be that fstat() does not fail, as expected. So what I really want is a way to tell if the descriptor is a pipe - fstat returns st_mode=0 (was expecting S_IFIFO!)


Solution

  • If you don't read from the pipe, the subprocess is fairly likely to never terminate. The buffer between the ends of the pipe is fairly small. So, as the subprocess writes output, the buffer will fill and the subprocess will block in the write() call. Then you'll have deadlock. The parent process is waiting for the subprocess to terminate before reading from the pipe, the subprocess is blocked until the parent process reads from the pipe and so can't terminate.