Search code examples
cpipefork

fork() and pipe() in C goes wrong


I am learning about fork and pipe but have a problem with the following: My aim was to build a program with 3 processes and I did that but my question is: Why does printf("Sum of first half: %d\n", sum); get executed twice?

I checked the code for any logical errors that I made but couldn't find anything.

#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);
    }
}

Solution

  • Your code simplified:

    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");
    }
    

    And the explanation:

    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