Search code examples
clinuxoperating-systemforkwait

how the child in this program will run?


I don't fully understand the fork function,i don't get how the father and child process contineo from fork() function or the skip this line and go to the next one. for example:

int value = 0;
if (fork()!=0)
{
 wait(&value);
 value = WEXITSTATUS(value);
 value++;
}
printf("%d\n",value);
value+=2;
exit(value);

when we implement the fork function the father go for wait() function but what i don't understand that from where the child start to run from the if() or he escape it and go immediately for the printf? Thanks for helping :)


Solution

  • The whole program is duplicated and both father and son start from fork() The father enter inside the if because its fork return value is non null, and after go to

    printf("%d\n",value);
    value+=2;
    exit(value);
    

    while the son just go to this line, because is pid is zero.

    The son exits 2 because of line value += 2.

    The father waits for that value (ie value = 2), increment it (value = 3), and then add 2 (value = 5).