带有stdout和stdin管道的Python Popen:读取冻结

时间:2015-10-21 13:51:18

标签: python c linux pipe subprocess

我目前面临一个奇怪的问题。我想用Python管理这个简单二进制文件的执行:

int main()
{
        char test[5];
        printf("Reading\n");
        fgets(test, 5, stdin);
        printf("Data read : %s\n", test);
}

到目前为止我所做的是以下代码:

child = subprocess.Popen("./example.bin", stdout=subprocess.PIPE, stdin=subprocess.PIPE)
child.stdout.readline()

我的问题是为什么readline()永远阻止?我的意思是,我知道fgets()函数将等待输入,但在标准终端中,"读取\ n"字符串在开始等待用户输入之前正确打印。

另外,我关于在stdin上阻塞的fgets(),实际上是与stdout(/ dev / ttyX)相同的文件描述符。然后,我明白在stdin上阅读可以阻止stdout。但是,child.stdout是一个BufferedIO,应该已经接收到printf()发送的数据。我试图分离()stdout希望在对它执行readline()之前切断与文件描述符的链接,但没有成功。

我读了很多关于管道,tty等等的东西。不幸的是,我似乎在这里遗漏了一些东西。我也尝试过很多不同的参数,比如bufsize = 0,shell = True等.communication()函数写入数据并关闭child.stdin,这不是我想做的事情(在我的真实程序中,我有更多的fgets( )/ printf()调用)。

最后,如果我写入child.stdin,请刷新它,检查进程是否已使用poll()终止,child.stdout最终可读。

此外,这种死锁问题似乎只在我管道stdin和stdout时发生。

有谁知道如何解决这个问题?如何阅读已经打印过的数据"在阅读之前?

提前谢谢!

0 个答案:

没有答案
相关问题