将stdout重定向到C中的管道 [英] Redirecting stdout to pipe in C
本文介绍了将stdout重定向到C中的管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我要制作的程序:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char* argv[])
{
char* arguments[] = {"superabundantes.py", NULL};
int my_pipe[2];
if(pipe(my_pipe) == -1)
{
fprintf(stderr, "Error creating pipe\n");
}
pid_t child_id;
child_id = fork();
if(child_id == -1)
{
fprintf(stderr, "Fork error\n");
}
if(child_id == 0) // child process
{
close(my_pipe[0]); // child doesn't read
dup2(my_pipe[1], 1); // redirect stdout
execvp("cat", arguments);
fprintf(stderr, "Exec failed\n");
}
else
{
close(my_pipe[1]); // parent doesn't write
char reading_buf[1];
while(read(my_pipe[0], reading_buf, 1) > 0)
{
write(1, reading_buf, 1); // 1 -> stdout
}
close(my_pipe[0]);
wait();
}
}
我想在子级中执行exec,将子级的stdout重定向到父级(通过管道).我认为问题可能与dup2有关,但我以前从未使用过.
I want to execute the exec in the child redirecting the stdout of the child to the parent (through the pipe). I think the problem might be related to dup2, but I haven't used it before.
推荐答案
调用exec时,还需要 提供argv[0]
.因此,您的论据应为:
You need to also provide argv[0]
when you call exec. So your arguments should read:
char* arguments[] = {"cat", "superabundantes.py", NULL};
这篇关于将stdout重定向到C中的管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文