2013-01-24 56 views
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... 

回答

0

添加到您的Python腳本:

sys.stdout.flush() # after printing to stdout 
sys.stderr.flush() # after printing to stderr 

(行緩衝是TTY設備的默認,而不是管道)。

在你要檢測在父進程的管道(和/或子女)EOF未來,你將不得不關閉在父母的管道兩端未使用的,太。編輯:並關閉其他您的管道未使用的一端在子進程中。

/* This should be in parent as well */ 
close(pipe_in[0]); 
close(pipe_out[1]); 

/* This should be added to the child */ 
close(pipe_in[1]); 
close(pipe_out[0]); 
+0

我不敢相信這只是一個沒有刷新的緩衝區。謝謝!這完全奏效。 – Steve

+0

有什麼辦法可以告訴Python不要緩衝標準輸出嗎? – Steve

+0

@Steve下手吧'蟒蛇-u'(它禁用標準輸入,標準輸出,標準錯誤緩衝完全) –