将标准输出重定向到 C 中的管道

Xav*_*olf 5 c redirect fork stdout pipe

这是我正在尝试制作的程序:

#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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我想在子进程中执行 exec,将子进程的 stdout 重定向到父进程(通过管道)。我认为问题可能与dup2有关,但我之前没有使用过。

kmk*_*lan 3

当您调用 exec 时,您需要提供。argv[0]所以你的论点应该是:

char* arguments[] = {"cat", "superabundantes.py", NULL};
Run Code Online (Sandbox Code Playgroud)