简体   繁体   English

管道未收到子进程的所有输出

[英]Pipe is not receiving all output from child process

I wanted to open up a pipe to a program and read output from it. 我想打开到程序的管道并从中读取输出。 My initial inclination was to use popen(), but the program takes a number of options, and rather that fighting with shell quoting/escaping, I decided to use a combination of pipe(), fork(), dup() to tie the ends of the pipe to stdin/stdout in the parent/child, and execv() to replace the child with an invocation of the program passed all of the options it expects as an array. 我最初的想法是使用popen(),但是该程序采用了许多选项,为了避免与shell引号/转义,我决定使用pipe(),fork(),dup()的组合来绑定到父/子中的stdin / stdout的管道的两端,以及通过调用程序期望的execv()将子代替换为程序,并将其期望的所有选项作为数组传递。

The program outputs many lines of data (and flushes stdout after each line). 程序输出多行数据(并在每行之后刷新stdout)。 The parent code sets stdin to non-blocking and reads from it in a loop using fgets(). 父代码将stdin设置为非阻塞,并使用fgets()在循环中从其读取数据。 The loop runs while fgets() return non-NULL or stdin has an error condition that is EAGAIN or EWOULDBLOCK. 当fgets()返回非NULL或stdin的错误条件为EAGAIN或EWOULDBLOCK时,循环运行。

It receives most of the lines successfully, but towards the end it seems to drop off, with the last fgets() failing with an odd error of "No such file or directory." 它成功地接收了大多数行,但是到最后它似乎下降了,最后一个fgets()失败,出现奇怪的错误:“没有这样的文件或目录”。

Does anyone know what I might have done wrong here? 有谁知道我在这里做错了什么?

I found the problem. 我发现了问题。 I stupidly was not resetting errno to zero each iteration. 我愚蠢的是没有将errno重置为零。 I guess I just assumed fgets() would take care of it or something... My stupid mistake. 我想我只是以为fgets()会解决这个问题……我的愚蠢错误。 Now it is working fine. 现在工作正常。 Always reset errno! 始终重置errno!

Thanks for the help anyway. 无论如何,谢谢您的帮助。

不确定,在linux上有一个很酷的函数叫做posix_spawn (示例在这里http://www.opengroup.org/onlinepubs/000095399/xrat/xsh_chap03.html#tag_03_03_01_02 )有时它使做管道更容易...但是听起来像可能的阻塞问题或管道...。

Make sure you open a pipe to STDERR. 确保打开通往STDERR的管道。 Most programs write error data there instead of STDIN. 大多数程序将错误数据写入那里,而不是STDIN。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM