管道流问题
我正在尝试执行我在 popen 中创建的程序,然后收集输出。我执行的程序需要 30 秒(有 30 个 sleep(1)),并且每一秒后都会发送输出块。让我困惑的是,当我调用 pipe = popen("test -flag", "r")
时,它立即完成并且 FILE 流管道为空。我的假设是程序将停止并等待测试完成执行然后再继续,或者它是否启动收集输出的命令并立即继续?如果是后者,有什么办法可以暂停程序,直到管道有所有输出后再继续?
谢谢!
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 for 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对
popen()
的调用应该相对较快,因此您的程序可以继续读取程序的输出。当然,popen()
本身并不等待被调用的程序完成。一旦popen()
返回,您的程序应该能够从文件流中读取;它会挂起,直到有输入等待,或者直到其他进程关闭管道(例如终止),此时它将收到 EOF 指示。然后,您可以pclose()
您正在读取的流。当您直接运行测试程序并将其输出发送到管道时,测试程序的行为如何?请注意,当输出是管道(全缓冲)和终端(行缓冲)时,标准 I/O 的行为通常有所不同。
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 thepopen()
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 thenpclose()
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).
读取
pipe
直到返回EOF
。Read
pipe
untilEOF
is returned.