Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't processes split by fork() proceed through this function identically?

Tags:

c++

c

I am confused by the fork() function in C/C++. Given the following code:

void fork2()
{
    printf("LO\n");
    fork()
    printf("L1\n");
    fork();
    printf("Bye!\n");
}

Lecture slides give the following diagram

         ______Bye
   ___L1|______Bye
  |      ______Bye
L0|___L1|______Bye

To me, this diagram doesn't make any sense. I expect that each call to fork will result in a call to printf("LO\n"). Or am I wrong?

like image 222
newprint Avatar asked Nov 28 '22 03:11

newprint


1 Answers

You are wrong. When forking, both the parent and child process continue from the same place - after the call to fork(), not at the start of the function. It's easy to verify this behaviour - change your function's name to main() and then compile and run it:

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

int main(int argc, char **argv)
{
    printf("LO\n");
    fork();
    printf("L1\n");
    fork();
    printf("Bye!\n");

    return 0;
}

Output:

LO
L1
Bye!
L1
Bye!
Bye!
Bye!

There's nothing like actually trying something to figure out how it works...

like image 145
Carl Norum Avatar answered Dec 10 '22 11:12

Carl Norum