管道流问题

发布于 2024-10-29 15:32:30 字数 249 浏览 3 评论 0原文

我正在尝试执行我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终止放荡 2024-11-05 15:32:30

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 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).

人间不值得 2024-11-05 15:32:30

读取pipe直到返回EOF

Read pipe until EOF is returned.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文