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! ");
case 0 : /* Child */
printf("Child process, PID %d: ", getpid());
loc ++;
g --;
printf( " loc=%d g=%d ", loc, g);
printf("Child (%d) done, exiting ... ", getpid());
exit(EXIT_SUCCESS);
default : /* Parent */
#if 1
sleep(2); /* let the child run first */
#endif
printf("Parent process, PID %d: ", getpid());
loc --;
g ++;
printf( " loc=%d g=%d ", loc, g);
}
printf("Parent (%d) will exit now... ", getpid());
exit(EXIT_SUCCESS);

The preceding program (ch10/fork5) has an initialized global variable g and an initialized local variable loc. The parent process, after fork, sleeps for two seconds thus more-or-less guaranteeing that the child process runs first (this kind of synchronization is incorrect in production quality code; we shall address this point in detail later in this chapter). Both the child and parent processes work on the global and local variables; the key question here is this: will the data get corrupted?

Let's just run it and see:

$ ./fork5
Child process, PID 17271:
loc=9 g=6
Child (17271) done, exiting ...
Parent process, PID 17270: << after 2 sec >>
loc=7 g=8
Parent (17270) will exit now...
$

Well, the data variables are not corrupted. Again, the key point here is this: as the child has a copy of the parent's variables, all goes well. They change independently of one another; they do not step on each other's toes. So, consider this:

Fork rule #4: Data is copied across the fork, not shared.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.108.102