C 中的文件描述符和管道

File descriptors and pipe in C

我在 c 中有一个基本的管道,我已经向子进程发送了一个整数,子进程将这个数字增加 1 并将发送回父进程。 我的问题是:如果我在写入函数后立即关闭写入文件描述符,会发生什么情况?程序会显示1(正确输出是2

int main(){

    int p[2];

    pipe(p);

    int n=1;
    write(p[1], &n, sizeof(int));
    close(p[1]); // don't work => the output is 1

    if(fork() == 0) {
            read(p[0], &n, sizeof(int));
            n = n + 1;
            write(p[1], &n, sizeof(int));
            close(p[1]);
            close(p[0]);
            exit(0);
    }
    wait(0);
    read(p[0], &n, sizeof(int));
    close(p[0]);
    //close(p[1]);  works => the output is 2

    printf("%d\n", n);
    return 1;

}

正确的输出肯定不是2。当您在分叉之前关闭管道时,两个进程现在如何关闭 pipe[1]。当子进程试图写入管道时,它将无法写入。因此,父级将读取 1,因为 2 从未写入 pipe[1]