Processes - Doubt

Asked

Viewed 103 times

-6

To better understand the workings of the processes, 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 obtained was

411

Not quite what I expected.

  • after all how much is worth the value variable?
  • what is happening for sure?

1 answer

1

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

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

Then the two processes write their variable, without requiring the order in which this writing is made.

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

Both 411 and 114 are perfectly acceptable results.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.