Issue
#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?
Solution
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.
Answered By - ikegami Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.