Fork rule #4 – data

When a parent process forks, we understand that the child is created; it is a copy of the parent. This will include the VAS, and, thus, the data and stack segments. Keeping this fact in mind, check out the following code snippet (ch10/fork5.c):

static int g=7;[...]int main(int argc, char **argv)    [...]    int loc=8;    switch((ret = fork())) {    case -1 : FATAL("fork failed, aborting!\n");    case 0 : /* Child */          printf("Child process, PID %d:\n", getpid());          loc ++;          g --;          printf( " loc=%d g=%d\n", loc, g);          printf("Child (%d) done, exiting ...\n", getpid());          exit(EXIT_SUCCESS);    default : /* Parent */    #if 1          sleep(2); /* let the child run first */    #endif          printf("Parent process, PID %d:\n", getpid());          loc --;          g ++; printf( " loc=%d ...

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.