Processes - Doubt

-6

To better understand how processes work, fork, I wrote this test program:

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

int main(){

   int value = 9 ;
   int pid = fork();

   if(pid==0) value+=2 ;
       else  value-=5 ;

   printf("%d",value);
}

The output was

411

This was not quite what I expected.

  • how much is the value variable worth?
  • What is certainly happening?
asked by anonymous 14.04.2016 / 03:50

1 answer

1

After fork() (if there was no error) there are two distinct variables with name value . One is in the original process (with 9 value), another is in the child process (also with 9 value).

if (pid == 0) does different things in 2 active processes. One of them increases 2 to its valor and in the other it decreases 5 to other valor .

Then the two processes write their variable, without request of the order by which this writing is done.

One of the processes has valor with 4 (9 - 5), another has 11 (9 + 2).

Both 411 and 114 are perfectly acceptable results.

    
17.04.2016 / 13:08