Donacdum
Donacdum

Reputation: 13

How is fork() able to produce varied results?

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

int main()
{
    int x = 1;

   /* fork off a child process */
    if (fork()==0)
       x++;

    /* fork off another child process */
    if (fork()==0)
       x++;

    printf("x = %d : ", x); fflush(stdout);

    /* wait for a signal to be received */
    pause();
}

This gives different results every time I run it. I've tried reading about why, but I'm having trouble wrapping my head around it. What are the possible outputs of this? And why?

Upvotes: 1

Views: 53

Answers (1)

ikegami
ikegami

Reputation: 386561

The output of each process is completely deterministic (assuming no errors).

P1                        P11                       P111
+----------------+        + - - - - - - - -+        + - - - - - - - -+
|  x = 1;        |        :  x = 1;        :        :  x = 1;        :
|  fork(); // !0 |------->:  fork(); // =0 :        :  fork(); // =0 :
|  fork(); // !0 |---+    |  ++x;          |        :  ++x;          :
|  printf();     |   |    |  fork(); // !0 |------->:  fork(); // =0 :
+----------------+   |    |  printf();     |        |  ++x;          |
                     |    +----------------+        |  printf();     |
                     |                              +----------------+
                     |
                     |    P12
                     |    + - - - - - - - -+
                     |    :  x = 1;        :
                     |    :  fork(); // !0 :
                     +--->:  fork(); // =0 :
                          |  ++x;          |
                          |  printf();     |
                          +----------------+
  • P1 outputs 1.
  • P11 outputs 2.
  • P111 outputs 3.
  • P12 outputs 2.

However, depending on variations in scheduling, the order in which each process's output appears is unpredictable.

Upvotes: 2

Related Questions