You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何父进程需等待子进程输入后才能正确读取管道数据?

问题解析:父进程为何会等待子进程输入后才执行

我写了这段代码,原本以为父子进程是独立运行的,父进程应该会直接从管道读取到乱码并打印,但实际情况是父进程会一直等子进程获取用户输入后,才正确打印出数据。想知道这是为什么?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    int pipe_fd[2];
    if (pipe(pipe_fd) == -1) {
        perror("pipe");
        return 1;
    }

    pid_t child_pid = fork();
    if (child_pid == -1) {
        perror("fork");
        return 1;
    }

    if (child_pid == 0) {
        // 子进程
        close(pipe_fd[0]); // 关闭子进程的读端
        
        int numberToSend;
        printf("Enter a number to send to parent: ");
        scanf("%d", &numberToSend);
        
        write(pipe_fd[1], &numberToSend, sizeof(numberToSend));
        close(pipe_fd[1]);
        exit(0);
    } else {
        // 父进程
        close(pipe_fd[1]); // 关闭父进程的写端
        int receivedNumber;
        read(pipe_fd[0], &receivedNumber, sizeof(receivedNumber));
        close(pipe_fd[0]);

        printf("Parent received number: %d\n", receivedNumber);
    }

    return 0;
}

原因说明

核心原因是管道的read操作的阻塞特性:

  • 当父进程调用read(pipe_fd[0], ...)时,管道里还没有任何数据,且子进程的写端(pipe_fd[1])仍处于打开状态(子进程要等用户输入后才会写入并关闭)。
  • 根据Unix管道的规则,当管道为空且仍有写端处于打开状态时,read调用会阻塞当前进程,直到有数据写入管道,或者所有写端都被关闭。

父子进程确实是独立运行的,但管道作为它们之间的通信机制,通过这种阻塞特性实现了同步:父进程的read会一直等待,直到子进程把数据写入管道,此时read才会读取到数据并返回,父进程才会继续执行后续的打印操作。

你之前以为会读到乱码,是忽略了管道read的阻塞行为——它不会在没有数据的时候返回垃圾数据,而是会等待数据到来。

内容的提问来源于stack exchange,提问作者pyronic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 08:28:18