Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用pipe/dup2与Python子流程通信_C_Posix_Dup2 - Fatal编程技术网

C 使用pipe/dup2与Python子流程通信

C 使用pipe/dup2与Python子流程通信,c,posix,dup2,C,Posix,Dup2,我想使用Python为我的C程序实现一个用户界面。然而,我似乎无法让沟通正常进行。以下是我到目前为止所做的,test.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

我想使用Python为我的C程序实现一个用户界面。然而,我似乎无法让沟通正常进行。以下是我到目前为止所做的,
test.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
是:

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...

添加到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]);

啊,我真不敢相信这只是一个没有冲洗的缓冲区。非常感谢。这完全奏效了。有没有办法告诉Python不要缓冲标准输出?@Steve从
Python-u
开始(它完全禁用stdin、stdout和stderr缓冲)