我使用subprocess在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;
}
Run Code Online (Sandbox Code Playgroud)
我用这个python片段调用这个小程序:
import os
import subprocess
read, write = os.pipe()
proc = subprocess.Popen(["./dummy", str(write)])
data = os.fdopen(read, "r").read()
print data
Run Code Online (Sandbox Code Playgroud)
read()方法不返回,因为fd未关闭.在python中打开和关闭write fd解决了这个问题.但这对我来说似乎是个黑客.有没有办法在我的C++过程中关闭fd?
非常感谢!
在Linux上生成子进程(所有POSIX操作系统,实际上)通常是通过fork和完成的exec.之后fork,两个进程都打开了文件.C++进程关闭它,但文件保持打开状态,直到父进程也关闭fd.这对于使用的代码来说是正常的fork,通常由包装器处理fork.阅读man页面pipe.我猜python无法知道哪些文件正在传输给孩子,因此不知道在父进程和子进程中要关闭什么.
| 归档时间: |
|
| 查看次数: |
1518 次 |
| 最近记录: |