在C语言中如何将标准输出重定向到管道?

6
下面是一个我正在尝试制作的程序:
#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,并将子进程的标准输出重定向到父进程(通过管道)。我认为问题可能与dup2有关,但我以前没有使用过它。

请明确指出“问题”是什么,而不是只是把代码倒出来让我们自己找。如果您不知道问题在哪里,请向程序添加错误报告。 - Fred Foo
不要解决你的问题,但是你必须为wait()函数指定一个int *sts(可以为NULL)。 - André A. G. Scotá
谢谢!更改后完美运行。 char* arguments[] = {"cat', "superabundantes.py", NULL}; - user1932637
2个回答

3

在调用exec时,您还需要提供argv [0]。因此,您的参数应该如下:

char* arguments[] = {"cat", "superabundantes.py", NULL};

是的!你说得对。char* arguments[] = {"cat", "superabundantes.py", NULL}; execvp(argv[0], arguments); 它完美地运行了,谢谢你。 - XavierusWolf

-2
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>



int main(int argc, char* argv[])
{
    //char* arguments[] = {"cat","tricky.txt", NULL};
    char* arguments[] = {"./son1", 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(arguments[0], 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();
   }

}

/* 如果./son1返回 则son1中的printf()将由父进程中的write(1 ..)输出 如果son1处于死循环状态,则son1中的printf()将不会被父进程中的write(1 ..)输出

void main()
{
    printf( "***** son run *****\n\r" );
    return;
    while(1);
}

有什么想法吗?
*/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接