C 中的 fork() 和 pipe() 出错

fork() and pipe() in C goes wrong

我正在学习 fork 和 pipe,但遇到以下问题:我的目标是构建一个包含 3 个进程的程序,我做到了,但我的问题是:为什么 printf("Sum of first half: %d\n", sum); 被执行两次?

我检查了代码是否有我犯的任何逻辑错误,但找不到任何东西。

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

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int size = sizeof(arr) / sizeof(int);
    int sum;

    int fd[2];
    pipe(fd);

    int id = fork();

    if (id == 0) // Child process
    {
        for (int i = 0; i < size / 2; i++)
            sum = sum + arr[i];

        int j = fork();
        if (j == 0)
        {
            printf("Hello I'm the grandchild\n");
        }
    }

    else // Parent process
    {
        for (int i = size / 2; i < size; i++)
            sum = sum + arr[i];
    }

    if (id == 0) // Child process writing to the pipe
    {
        close(fd[0]);
        write(fd[1], &sum, sizeof(sum));
        close(fd[0]);
        printf("Sum of first half: %d\n", sum);
    }

    else // Parent process reading from the pipe
    {
        int x;
        close(fd[1]);
        read(fd[0], &x, sizeof(sum));
        close(fd[1]);
        printf("Sum of second half: %d\n", sum);
        printf("Total sum: %d\n", x + sum);
    }
}

您的代码已简化:

int main()
{
    int id = fork();

    if (id == 0)
        fork();

    if (id == 0)
        printf("Sum of first half\n");
    else
        printf("Sum of second half\n");
}

以及解释:

code Parent Child Granchild
fork() fork N/A N/A
id value id != 0 id==0 N/A
if (id == 0) fork() then not executed fork N/A
id value id != 0 id == 0 id == 0
if (id == 0) printf("sum first") then not executed printf printf
else printf("sum second half") printf else not executed else not executed