Pipe Stream Question
I am trying to execute a program I created in popen and then collect the output. The program I execute takes 30 seconds (there are 30 sleep(1)s) and after each seconds it sends chunks of output. What puzzles me is that when I call pipe = popen("test -flag", "r")
it finishes immediately and the FILE stream pipe is empty. Are my assumptions that that the program will halt and wait f开发者_运维百科or test to finish executing before continuing or does it initiate the order to collect the output and immediately continue on? If it is the latter, is there any way to pause the program until the pipe has all the output before continuing?
Thanks!
The call to popen()
is supposed to be relatively quick, so your program can get on with reading the output from the program. Certainly, popen()
itself does not wait for the invoked program to finish. Once the popen()
returns, your program should be able to read from the file stream; it will hang until there is input waiting, or until the other process closes the pipe (e.g. terminates), at which point it will get an EOF indication. You can then pclose()
the stream you were reading from.
How does your test program behave when you run it directly with its output sent to a pipe? Note that standard I/O typically behaves differently when the output is a pipe (full buffering) as against a terminal (line buffering).
Read pipe
until EOF
is returned.
精彩评论