我使用子進程在python中產生進程,並且想要使用管道從程序中讀取輸出。 C++程序似乎並沒有關閉管道,即使明確告訴它關閉。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;
}
我調用該小程序與此蟒片段:
import os
import subprocess
read, write = os.pipe()
proc = subprocess.Popen(["./dummy", str(write)])
data = os.fdopen(read, "r").read()
print data
讀()方法不返回,因爲FD未關閉。在python中打開和關閉寫入fd可解決問題。但對我來說,這似乎是一個詭計。有沒有辦法在我的C++過程中關閉fd?
非常感謝!
有趣。意味着在構建「Popen」對象後關閉文件描述符? – krlmlr
@ user946850:請參閱http://linux.die.net/man/2/pipe –
上的示例代碼請參閱Python文檔中的示例:http://docs.python.org/library/subprocess.html #replacement-shell-pipeline。 「啓動p2後,p1.stdout.close()調用非常重要,以便p1在p1之前退出時接收SIGPIPE。」這意味着,是的,請關閉Python進程中的句柄。 – krlmlr