Python 和 C++ 之间的管道不会关闭

Pipes between Python and C++ don't get closed

本文关键字:管道 C++ 之间 Python      更新时间:2023-10-16

我正在使用子进程在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中打开和关闭写fd可以解决这个问题。但这对我来说似乎是一个黑客。有没有办法在我的C++过程中关闭 fd?

多谢!

在 Linux 上生成一个子进程(实际上所有 POSIX 操作系统)通常通过 forkexec 来完成。 fork 后,两个进程都会打开文件。 C++进程关闭它,但文件保持打开状态,直到父进程也关闭 fd。 这对于使用fork的代码来说是正常的,通常由fork周围的包装器处理。 阅读man页面了解pipe。 我想python无法知道哪些文件正在传输到子进程,因此不知道在父进程与子进程中要关闭什么。

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

也许最简单的方法是让C++进程将其输出写入stdout(如cout <<),Python 使用 stdout=PIPE 调用Popen并读取proc.stdout(或使用 proc.communicate() 而不是使用 fdopen )。这应该也适用于Windows。

有关将文件描述符作为命令行参数传递的信息,请参阅 Ben Voigt 的答案。