On Monday 06 November 2006 17:54, Kasicass wrote: > Hi all, > > I just run the following program in obsd 3.9, but it doesn't work as > expected. As said that child process created by vfork should run in the > address space of the parent, until it calls exec/exit. > > --------- > #include <sys/types.h> > #include <unistd.h> > #include <stdio.h> > #include <stdlib.h> > > 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 fork\n"); /* we don't flush stdout */ > > if ( (pid = vfork()) < 0 ) > ; > else if (pid == 0) > { /* child */ > glob++; /* modify variables */ > var++; > _exit(0); /* child terminates */ > } > > printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var); > exit(0); > } > --------- > In obsd, result is > > before fork > pid = xxx, glob = 7, var = 89 > > But in Linux 2.6/FreeBSD 5.4-RELEASE, it works fine. The result is > > before fork > pid = xxx, glob = 6, var = 88 > --------- > > Could anyone give me a brief description about why it runs like that ?
The following excerpt is taken from the Linux man page for vfork. (From SUSv2 / POSIX draft.) The vfork() function has the same effect as fork(), except that the behaviour is undefined if the process cre- ated by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit() or one of the exec() family of functions. Of note here is "the behaviour is undefined if the process created by vfork() ... modifies any data other than a variable of type pid_t used to store the return value from vfork()". I can't answer why OpenBSD differs (although I could make some educated guesses) but either implementation is correct if going by the above excerpt. -- Jason Stubbs