小编Xav*_*olf的帖子

将标准输出重定向到 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, …
Run Code Online (Sandbox Code Playgroud)

c redirect fork stdout pipe

5
推荐指数
1
解决办法
3万
查看次数

为什么在C中重定向stdin不起作用?

我正在尝试通过管道"my_pipe"将stdin从父级重定向到子级,但是当我运行程序时,我看不到预期的结果.

当我执行程序时,它期望从stdin输入,那么为什么它没有重定向在dup2中的stdin?

#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], …
Run Code Online (Sandbox Code Playgroud)

c stdin fork pipe exec

2
推荐指数
1
解决办法
5782
查看次数

标签 统计

c ×2

fork ×2

pipe ×2

exec ×1

redirect ×1

stdin ×1

stdout ×1