【问题标题】:Why does redirecting stdin in C not work?为什么在 C 中重定向标准输入不起作用?
【发布时间】:2012-05-29 05:01:51
【问题描述】:

我正在尝试通过管道“my_pipe”将标准输入从父级重定向到子级,但是当我运行我的程序时,我没有看到预期的结果。

当我执行程序时,它期望来自标准输入的输入,那么为什么它不在 dup2 中重定向标准输入?

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



int main(int argc, char* argv[])
{
    char* arguments[] = {"sort", 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[1]); // child doesn't write
        dup2(0, my_pipe[0]); // redirect stdin

        execvp(argv[0], arguments);

        fprintf(stderr, "Exec failed\n");
    }
    else
    {
        close(my_pipe[0]); // parent doesn't read

        char reading_buf[1];
        write(my_pipe[1], "hello", strlen("hello"));
        write(my_pipe[1], "friend", strlen("friend"));
        close(my_pipe[1]);
        wait();
    }
}

【问题讨论】:

    标签: c exec fork pipe stdin


    【解决方案1】:

    您对 dup2 的论点是倒退的。试试dup2(my_pipe[0], STDIN_FILENO)

    【讨论】:

    • 是的!做到了!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多