c - 为什么父进程首先从 LINUX 中的管道读取

标签 c linux

我运行了这段代码,发现父进程先读取,然后子进程写入。我想知道为什么会这样?
另外我还想知道如何在这个程序中使用两个管道。我只是想要概念,任何代码都会受到赞赏。谢谢

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

    main()
    {
            int     fd[2];
            pid_t   childpid;

            pipe(fd);

            if((childpid = fork()) == -1)
            {
                    perror("fork");

            }

            if(childpid == 0)
            {
                    /* Child process closes up input side of pipe */
                    close(fd[0]);
        printf("\nChild writes\n\n");
            }
            else
            {
                    /* Parent process closes up output side of pipe */
                    close(fd[1]);
        printf("parent reads\n\n");
            }
            return 0;
    }

最佳答案

对于您的查询:-

父进程先读取,然后子进程写入。我想知道为什么会这样

fork()后两个进程独立工作,所以先调度哪个进程,这取决于调度器。

如何在此程序中使用两个管道?

打开两个管道,一个给父进程,一个给子进程。因为管道是单向的。

int fd[2];
int fd1[2];

parents will write on fd[1]  child will read from fd[0]
child will write on fd1[1] parents will read from fd1[0]

关于c - 为什么父进程首先从 LINUX 中的管道读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40757631/

相关文章:

c - GCC 的 "-Wl,option"和 "-Xlinker option"语法有区别吗?

c++ - 关闭套接字如何影响其他方读取

c - 使用函数在数组中查找最大和最小数

c - 如何一次将数组中的数字复制到二进制文件中?

linux - 如何向网页发送信号

使用 PyCharm 在远程服务器上进行 Python 绘图

java - 使用 Linux 用户权限限制应用程序存储在磁盘中的数据访问

c - 为什么 `x && y` 没有被解析为 `x & (&y)` ?

java - 如何使用防火墙/iptables 在不中断的情况下重启 Java 服务?

linux - ARM 是否在 NEON 运行时闲置?