2013-01-24 2 views
0

파이썬을 사용하여 C 프로그램을위한 사용자 인터페이스를 구현하고 싶습니다. 그러나 커뮤니케이션이 제대로 작동하지 않는 것 같습니다. 여기에 내가 지금까지 test.c를 수행 한 작업은 다음과 같습니다,pipe/dup2를 사용하여 파이썬 서브 프로세스와 통신하기

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 

하지만 그 대신, 그것은 단순히 :

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 것은 후에 걸림 받음,

Starting up Python interface... 

답변

0

파이썬 스크립트에 추가

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

파이썬에게 표준 출력을 버퍼하지 않게 할 방법이 있습니까? – Steve

+0

@Steve는'python -u'로 시작합니다 (stdin, stdout, stderr는 완전히 버퍼링되지 않습니다). –

관련 문제