0
我想使用Python爲我的C程序實現用戶界面。但是,我似乎無法讓溝通工作。這是我到目前爲止已經完成,test.c
:使用pipe/dup2與Python子進程通信
int main()
{
int pipe_in[2], pipe_out[2];
if (pipe(pipe_in) != 0 || pipe(pipe_out) != 0)
{
perror("pipe");
return 1;
}
int _proc_handle = 0;
if ((_proc_handle=fork()) == 0)
{
printf("Starting up Python interface...\n");
dup2(pipe_in[0], STDIN_FILENO);
dup2(pipe_out[1], STDOUT_FILENO);
close(pipe_in[0]);
close(pipe_out[1]);
execlp("python", "python", "interface.py", (char*)NULL);
perror("execlp");
printf("Error executing Python.\n");
exit(1);
}
_write_fd = pipe_in[1];
_read_fd = pipe_out[0];
sleep(1);
char buffer[256];
int n = read(_read_fd, buffer, 11);
printf("n: %d\n", n);
printf("buffer: `%s'\n", buffer);
write(_write_fd, "from C\n", 5);
return 0;
}
和interface.py
是:
import sys
import time
time.sleep(0.1)
print >>sys.stdout, 'from python'
print >>sys.stderr, sys.stdin.readline()
運行此,我希望它打印,
Starting up Python interface...
n: 11
buffer: `from python'
from C
但是,相反,它只是掛起後,
Starting up Python interface...
我不敢相信這只是一個沒有刷新的緩衝區。謝謝!這完全奏效。 – Steve
有什麼辦法可以告訴Python不要緩衝標準輸出嗎? – Steve
@Steve下手吧'蟒蛇-u'(它禁用標準輸入,標準輸出,標準錯誤緩衝完全) –