Skip to content
Advertisement

Explain pipe and fork output

I am dealing with pipe and fork in Linux for the first time and I would be happy if someone could explain to me the output of the following program: (which line of code causes the output and is it through the son process or the parent process)

int main(){                              //1
    int ipc[2];                          //2
    pipe(ipc);                           //3
    write(2, "startn", 6);              //4
    if (fork()) {                        //5
        sleep(1);                        //6
        char c;                          //7
        do {                             //8
            read(ipc[0], &c, 1);         //9
            write(1, &c, 1);             //10
        } while (c != 'n');             //11
        write(1, "ifn", 3);             //12
        waitpid(-1, NULL, 0);            //13
    }                                    //14
    else {                               //15
        write(ipc[1], "else1n", 6);     //16
        write(1, "else2n", 6);          //17
    }                                    //18
    write(1, "donen", 5);               //19
    return 0;                            //20
}                                        //21

The output of the program is:

start
else2
done
else1
if
done

Advertisement

Answer

fork() creates a child process executing the same code as the original process. If it succeeds, the only difference between your two processes is that:

  • in the original process, fork will return a non-zero value (i.e. the id of the child process)
  • in the child process, fork will return a zero value

So, in other words: when you write:

if (fork()) {
    // Block "If"
} else {
    // Block "Else"
}

the original process will execute the “block if” and the child process will execute the “block else”.

pipe returns two file descriptors, one that can be used to write into the pipe, and the other one that can be used to read from the pipe. So when you write:

int ipc[2];
pipe(ipc);

Whatever you write in ipc[1] can be read when you read ipc[0]. In other words, that’s a good way to communicate between the two process created by fork.

In your example the child process (in the “else”) writes data in ipc[1] and the original process (in the “if”) reads it.

You created a child process writing data in a pipe while your original process reads data from the pipe.

Advertisement