Search code examples
cforkconcept

Fork concept, dont quite grasp how fork works


I try to draw out the process according to the code but I really need some explanation in why, here is the question:

B() {
     pid_t pid;
     if ((pid = fork()) != 0)
         waitpid(pid,NULL,0);
     printf("2");
     if(fork() ==0)
       { printf("3"); exit(0); }
     printf("5");
     exit(0);
}

Which one are illegals output?
232553, 235325, 232355, 235253, 252533...

This is the process I draw out according to the code and my understanding of fork.

            ___3 (exit so no more here)
           |
      __2__|___5 (I guess 5 should be here)
     |          |        
     |          |
 ____|____(wait)|(start again since printf 3 process end)

So I'm stuck right there... Any help is appreciated.


Solution

  • Okay, there are two forks. Here is control flow, from left to right, with parents on top and children on the bottom:

        +-- B ---- waitpid() --+                  +-- "5" -- E
        |                      |                  |
    A --+ fork()               +-- C -- "2" -- D -+ fork()
        |                      |                  |
        +----------------------+                  +-- "3" -- F
    

    So, what do we know?

    • "2", "5", and "3" each appear twice (90 possibilities)

    • No prefix may contain more "3" than "2" (30 possibilities)

    • No prefix may contain more "5" than "2" (16 possibilities)

    • The second "2" must be preceded by the first "5" (7 possibilities)

    The 7 possibilities are:

    2,3,5,2,3,5
    2,3,5,2,5,3
    2,5,2,3,3,5
    2,5,2,3,5,3
    2,5,2,5,3,3
    2,5,3,2,3,5
    2,5,3,2,5,3