c - 通过 pipe() C 调用与 python 交互的问题

标签 c linux pipe

我正在尝试为 Linux 编写一个 C 程序,它可以通过 pipe() 调用与其他程序交互。以下代码不起作用,但是如果我将“/usr/bin/python”更改为“/bin/cat”,则完全相同(我的意思是,该行已打印出来)

#include <unistd.h>
#include <sys/prctl.h>
#include <signal.h>

int main()
{
        int inpipe[2], outpipe[2], pid, in_bytes;
        char *cmd[] = {"python", (char *) NULL}, buff[1024];
        pipe(inpipe);
        pipe(outpipe);

        pid = fork();
        if (pid == 0)
        {
                dup2(inpipe[1], 1);
                dup2(inpipe[1], 2);
                dup2(outpipe[0], 0);

                prctl(PR_SET_PDEATHSIG, SIGTERM);

                execve("/usr/bin/python", cmd, NULL);
        }
        close(inpipe[1]);
        close(outpipe[0]);

        write(outpipe[1], "print \"lol\"\n", 12);
        in_bytes = read(inpipe[0], buff, 1024);
        write(1, buff, in_bytes);

        close(inpipe[0]);
        close(outpipe[1]);
        return 0;
}

最佳答案

问题是 python 仅当输入为 tty 时默认表现得像 REPL。没有 tty,它只是一个 REP:

# Hangs until the pipe is closed with Ctrl+D
{ echo 'print "lol"'; cat; } | python

您有多种选择,具体取决于您想做什么。其中两个包括:

  1. 运行 python -i 而不是获取 REPL (char *cmd[] = {"python", "-i", (char *) NULL})。这将显示所有交互式提示等,因此您必须阅读更多数据。

  2. 关闭管道以便 Python 知道脚本已完成。这将使它执行它。

这里是你的代码适合这样做:

#include <unistd.h>
#include <sys/prctl.h>
#include <signal.h>

int main()
{
        int inpipe[2], outpipe[2], pid, in_bytes;
        char *cmd[] = {"python", (char *) NULL}, buff[1024];
        pipe(inpipe);
        pipe(outpipe);

        pid = fork();
        if (pid == 0)
        {
                dup2(inpipe[1], 1);
                dup2(inpipe[1], 2);
                dup2(outpipe[0], 0);
                close(outpipe[0]);
                close(outpipe[1]);

                prctl(PR_SET_PDEATHSIG, SIGTERM);

                execve("/usr/bin/python", cmd, NULL);
        }
        close(inpipe[1]);
        close(outpipe[0]);

        write(outpipe[1], "print \"lol\"\n", 12);
        close(outpipe[1]);
        in_bytes = read(inpipe[0], buff, 1024);
        write(1, buff, in_bytes);

        close(inpipe[0]);
        close(outpipe[1]);
        return 0;
}

关于c - 通过 pipe() C 调用与 python 交互的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55525124/

相关文章:

java - 从命名的 Linux 管道读取 BufferedInputStream 只能工作一次

c - 指针数组指向另一个数组

C++:如何修改全局字符串?

c++ - 为什么符号 malloc、__malloc 和 __libc_malloc 指向相同的代码地址?

java - Ant 不使用我的 JAVA_HOME 来查找 tools.jar

c - 将数据写入 fork 管道不起作用

c - 使用 dup2 重定向时出现空白字符串

c - 预计算指数 (exp) 表

c++ - 如何在 getstr() c++ ncurses 之后删除文本

linux - 换了一个不正确的时钟。现在 code::blocks 拒绝构建 "all is up to date"