我正在使用子进程在 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?
非常感谢!