【问题标题】:Redirecting stdout to pipe in C将标准输出重定向到 C 中的管道
【发布时间】:2012-05-28 21:10:16
【问题描述】:

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

#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有关,但我之前没有使用过。

【问题讨论】:

  • 请说明“问题”是什么,而不是仅仅转储您的代码让我们找出答案。如果您不知道问题出在哪里,请在您的程序中添加错误报告。
  • 不解决你的问题,但是你必须为wait()函数指定一个int *sts(可以是NULL)。
  • 谢谢!更改 char* arguments[] = {"cat', "superabundantes.py", NULL}; 后完美运行

标签: c redirect fork pipe stdout


【解决方案1】:
#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() 将由 parent 中的 write(1 ..) 输出 如果 son1 处于死循环中,则 son1 中的 printf() 不会被父级中的 write(1 ..) 输出

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

有什么想法吗?
*/

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 是的!你说得对。 char* arguments[] = {"cat", "superabundantes.py", NULL}; execvp(argv[0], 参数);效果很好,谢谢。
    猜你喜欢
    • 2016-04-26
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2018-05-15
    • 1970-01-01
    相关资源
    最近更新 更多