使用stdio和C++/Python的EOF管道问题
我在一个Python程序和一个C++程序之间的通信管道中遇到了一些关于EOF(文件结束符)和标准输入输出的问题。我不知道自己哪里做错了。当我的程序中出现EOF时,我会清空标准输入,然后在下一轮尝试读取新的一行。问题是:出于某种原因,getline函数在第二次运行时总是立即返回EOF,而不是等待Python进程的新输入……有人知道这是怎么回事吗?
好的,这是代码:
#include <string>
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main(int argc, char **argv) {
for (;;) {
string buf;
if (getline(cin,buf)) {
if (buf=="q") break;
/*****///do some stuff with input //my actual filter program
cout<<buf;
/*****/
} else {
if ((cin.rdstate() & istream::eofbit)!=0)cout<<"eofbit"<<endl;
if ((cin.rdstate() & istream::failbit)!=0)cout<<"failbit"<<endl;
if ((cin.rdstate() & istream::badbit)!=0)cout<<"badbit"<<endl;
if ((cin.rdstate() & istream::goodbit)!=0)cout<<"goodbit"<<endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max());
//break;//I am not using break, because I
//want more input when the parent
//process puts data into stdin;
}
}
return 0;
}
还有Python代码:
from subprocess import Popen, PIPE
import os
from time import sleep
proc=Popen(os.getcwd()+"/Pipingtest",stdout=PIPE,stdin=PIPE,stderr=PIPE);
while(1):
sleep(0.5)
print proc.communicate("1 1 1")
print "running"
1 个回答
1
在Python中,communicate
是一个一次性使用的功能。它会把你给的输入发送到一个进程,然后关闭输入流,并读取输出流,同时等待这个进程结束。
一旦使用了“沟通”,你就不能再用同一个进程“重启”这个管道。
另一方面,当你在管道的另一端读取到 EOF
时,就表示没有更多的数据可以读取了。任何尝试读取的操作都会立即返回 EOF
; 这时Python已经关闭了管道。
如果你想继续使用同一个管道进行沟通,就需要使用子进程的 stdin
和 stdout
成员,而不是 communicate
(不过要小心可能出现的死锁问题),并且要用其他方法来告诉C++那边该进行下一轮的处理,而不是依赖流的结束信号。