3

我正在使用子进程在 python 中生成一个进程,并希望使用管道从程序中读取输出。即使明确告诉它关闭,C++ 程序似乎也没有关闭管道。

#include <cstdlib>
#include <ext/stdio_filebuf.h>
#include <iostream>

int main(int argc, char **argv) {
  int fd = atoi(argv[1]);
  __gnu_cxx::stdio_filebuf<char> buffer(fd, std::ios::out);
  std::ostream stream(&buffer);
  stream << "Hello World" << std::endl;
  buffer.close();
  return 0;
}

我用这个 python 片段调用这个小程序:

import os                                                                                         
import subprocess                                                                                 

read, write = os.pipe()                                                                           
proc = subprocess.Popen(["./dummy", str(write)])                                                  
data = os.fdopen(read, "r").read()                                                                
print data                                                                                        

read() 方法不会返回,因为 fd 没有关闭。在python中打开和关闭write fd解决了这个问题。但这对我来说似乎是一个黑客行为。有没有办法在我的 C++ 进程中关闭 fd?

非常感谢!

4

2 回答 2

5

在 Linux(实际上是所有 POSIX 操作系统)上生成子进程通常是通过fork和完成的exec。之后fork,两个进程都打开了文件。C++ 进程将其关闭,但文件保持打开状态,直到父进程也关闭 fd。这对于使用 的代码来说是正常的fork,并且通常由fork. 阅读man页面pipe。我猜python无法知道哪些文件正在传输给子进程,因此不知道在父进程和子进程中要关闭什么。

于 2012-07-03T22:35:20.263 回答
3

POSIX 文件描述符是进程本地的。Python 工具中的文件描述符write在 C++ 进程中无效。

也许最简单的方法是让 C++ 进程将其输出写入stdout(like cout <<),然后 Python 调用Popenusingstdout=PIPE和 read proc.stdout(或 useproc.communicate()而不是 using fdopen。这在 Windows 中也应该可以工作。

如需将文件描述符作为命令行参数传递,请参阅Ben Voigt 的回答

于 2012-07-03T22:29:39.073 回答