PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 16, 2022

[FIXED] How is fork() able to produce varied results?

 August 16, 2022     c, fork, output     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing