我正在开发一个C ++应用程序,它启动Python子进程并尝试在父(C ++)和子(Python)之间建立通信。特别是我正在编写Python部分,以便与我没有编写的C ++应用程序集成,我无法改变。我已经实现了一个套接字解决方案来处理通信,但我还需要支持使用管道进行通信。
我的问题是我可以从Python写入stdout并且消息由C ++应用程序接收。但是,Python子进程无法读取父进程发送的消息。我试图推断出我认为与描述问题最相关的代码部分:
C ++
void startSubprocess(char* program, char** arguments)
{
int p_stdout;
int p_stdin;
int p_stderr;
int out[2];
int in[2];
int err[2];
char** arguments;
char* program;
pipe(out);
pipe(in);
pipe(err);
posix_spawn_file_actions_init(&action);
posix_spawn_file_actions_addclose(&action, out[1]);
posix_spawn_file_actions_addclose(&action, in[0]);
posix_spawn_file_actions_addclose(&action, err[0]);
posix_spawn_file_actions_adddup2(&action, out[0], 0);
posix_spawn_file_actions_adddup2(&action, in[1], 1);
posix_spawn_file_actions_adddup2(&action, err[1], 2);
std::vector<char *> vars_c(vars.size() + 1);
for (std::size_t i = 0; i != vars.size(); ++i) {
vars_c[i] = &vars[i][0];
}
vars_c[vars.size()] = NULL;
string cwd = __getcwd();
if (directory.size() > 0)
chdir(directory.c_str());
if (posix_spawnp(&pid, program, &action, NULL, arguments, vars_c.data())) {
cleanup();
pid = 0;
if (directory.size() > 0) chdir(cwd.c_str());
return false;
}
if (directory.size() > 0) chdir(cwd.c_str());
p_stdin = out[1];
p_stdout = in[0];
p_stderr = err[0];
}
void write(const char* buf, int len)
{
write(p_stdout, buf, len);
}
void read(char* buf, int len)
{
read(p_stdin, buf, len);
}
的Python
def writeMsg(msg):
sys.stdout.write(msg)
sys.stdout.flush()
def readMsg():
msg = sys.stdin.read()
当我运行应用程序时,父进程(C ++)读取Python子进程发送的消息。之后,Python子进程无法从sys.stdin读取。它一直等到超时。
当我运行C ++应用程序时,我可以看到out = [3,4]和in = [5,6]所以p_stdin = 6和p_stdout = 3。我正在Ubuntu 14.04中测试该应用程序。
我一直在尝试其他一些方法(使用os.fdopen和os.read)但没有成功。欢迎任何解决这个问题的建议。谢谢!
修改
我意识到我跳过一些重要信息来理解这个问题。主应用程序和Python子进程需要连续地进行通信,读取和写入消息以在循环中发送和接收直到终止。代码看起来像这样(仅用于描述目的):
C ++
int communicate()
{
// skip var init etc
// launch subprocess
startSubprocess(program, arguments);
while(1)
{
// read message sent by subprocess
read(msg, len);
if(msg == "quit")
break;
// part of the code that generates msg2
// send a message to subproc
write(msg2, len2);
}
return 1;
}
的Python
def communicate():
while True:
# generate msg to send to C++
writeMsg(msg)
msgRcv = readMsg()
if msgRcv == 'quit':
break
return
答案 0 :(得分:0)
我已经意识到sys.stdin.read()在返回消息之前一直挂到EOF。用
替换msg = sys.stdin.read()msg = sys.stdin.readline()
我的应用程序按预期工作。应用程序发送的消息由换行符分隔开来&#39; \ n&#39;这个方法适合我。在其他情况下,我认为使用
一次读取一个字符msg += sys.stdin.read(1)
将避免程序挂起等待EOF。
关于read和readline之间的这种差异,已有几个答案。不幸的是,在我尝试readline的测试中,客户端在阅读之前被父进程终止了。