c - 使用 pipeline/dup2 与 Python 子进程通信

标签 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_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]);

关于c - 使用 pipeline/dup2 与 Python 子进程通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14509123/

相关文章:

c++ - 将 0x1234 转换为 0x11223344

c - 子进程和父进程之间的 POSIX 信号量

c - 在 C 中的 dup2 之后使用 execvp 运行 pico

c - 未初始化信号量的值

bash - 打印 POSIX 字符类

c - 使用 dup2 使 C 程序执行诸如 'ls/bin | grep grep | grep b' 之类的命令时出现问题

c - 将 execvp 与 dup2 一起使用会引发 EFAULT 错误

编译错误(调用的函数不是对象)

使用 64 位 GCC 在 Cygwin 上编译 64 位 GSL

c - 静态链接中目标文件和库的排序