Play and learn 300 000+ tabs online

Friday, May 28, 2010

Fork Vfork Difference

int     glob = 6;       /* external variable in initialized data */

int
main(void)
{
int var; /* automatic variable on the stack */
pid_t pid;

var = 88;
printf("before vfork\n"); /* we don't flush stdio */
if ((pid = vfork()) < 0) {
err_sys("vfork error");
} else if (pid == 0) { /* child */
glob++; /* modify parent's variables */
var++;
_exit(0); /* child terminates */
}
/*
* Parent continues here.
*/
printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);
exit(0);
}

Running this program gives us

$ <span class="docEmphStrong">./a.out</span><br />before vfork<br />pid = 29039, glob = 7, var = 89<br />


Here, the incrementing of the variables done by the child
changes the values in the parent. Because the child runs in the address space of
the parent, this doesn't surprise us. This behavior, however, differs from
fork.



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.