读取子进程一旦有可用的就输出?
我一直在尝试各种方法(popen、管道+ fork/exec,...)来读取子进程的输出,所有这些方法都有效,但表现出相同的行为:每当我尝试使用 read
/fread
,仅当缓冲区完全满或子进程退出时才返回。我正在寻找一种更像套接字的行为:一旦有数据可用,就读取任意数量的数据。
我该怎么做?
I've been trying various methods (popen, pipes + fork/exec, ...) to read a child process' output, all of which are working, but exhibit the same behavior: whenever I try to read the output using read
/fread
, it only returns when the buffer is completely full, or when the child exits. I'm looking for a behavior that's more like that of sockets: reading any amount of data as soon as some is available.
How do I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说你不会。特别是,子进程将缓冲流,因为它不会将连接到管道的流视为“交互式”。由于缓冲发生在子进程内部,因此防止它的唯一方法是重写子进程中的代码,以防止它缓冲其标准输出(无论是在任何时候,还是在传递特定开关时,或者也许您可以添加代码检测它何时连接到管道并仅在特定情况下关闭缓冲)。但是,如果子进程向标准输出写入大量内容,则可能会影响子进程的性能(特别是如果您没有选择何时禁用缓冲)。
Generally you don't. In particular, the child process will buffer the stream because it won't see a stream connected to a pipe as being "interactive." Since the buffering is happening inside the child process, about the only way to prevent it is to rewrite the code in the child to prevent it from buffering its standard output (either ever, or when passed a particular switch, or perhaps you can add code to detect when it's connected to a pipe and turn off buffering only in that specific case). That, however, can affect the child's performance if it writes much to standard output (especially if you aren't selective about when you disable buffering).
我认为这是不可能的。缓冲是在子进程一侧处理的,如果它不刷新缓冲区,则没有任何内容可供您读取。然而,一些工具有命令行选项来控制缓冲,例如
grep --line-buffered
。I don't think that's possible. The buffering is handled on the child's side, and if it doesn't flush its buffers, there is nothing for you to read. However, a few tools have command line options to control the buffering, e.g.
grep --line-buffered
.