我正在尝试为 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
您有多种选择,具体取决于您想做什么。其中两个包括:
运行
python -i
而不是获取 REPL (char *cmd[] = {"python", "-i", (char *) NULL}
)。这将显示所有交互式提示等,因此您必须阅读更多数据。关闭管道以便 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/