读取子进程一旦有可用的就输出?

发布于 2024-09-12 17:24:21 字数 195 浏览 4 评论 0原文

我一直在尝试各种方法(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 技术交流群。

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

发布评论

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

评论(2

旧瑾黎汐 2024-09-19 17:24:21

一般来说你不会。特别是,子进程将缓冲流,因为它不会将连接到管道的流视为“交互式”。由于缓冲发生在子进程内部,因此防止它的唯一方法是重写子进程中的代码,以防止它缓冲其标准输出(无论是在任何时候,还是在传递特定开关时,或者也许您可以添加代码检测它何时连接到管道并仅在特定情况下关闭缓冲)。但是,如果子进程向标准输出写入大量内容,则可能会影响子进程的性能(特别是如果您没有选择何时禁用缓冲)。

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

风柔一江水 2024-09-19 17:24:21

我认为这是不可能的。缓冲是在子进程一侧处理的,如果它不刷新缓冲区,则没有任何内容可供您读取。然而,一些工具有命令行选项来控制缓冲,例如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.

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