Reputation: 13
#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
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(); |
+----------------+
1
.2
.3
.2
.However, depending on variations in scheduling, the order in which each process's output appears is unpredictable.
Upvotes: 2