vfork never return
Why this program will never return and continuing create child processes?
int main()
{
pid_t pid;
int foo1 = 1, foo2 = 2;
printf("before fork()\n");
if ((pid = vfork()) < 0 ) {
printf("fork failed.\n");
}else if (pid == 0) {
foo1++;
foo2++;
printf("child process: pid is %d, my parent pid is %d\n", getpid(), getppid());
}else if (pid > 0){
printf("parent process: pid is %d\n", getpid());
}
printf("%s: foo1 is %d, foo2 is %d\n",pid == 0 ? "child process" : "parent process", foo1, foo2);
return 0;
}
the output is like:
before fork()
child process: pid is 17244, my parent pid is 15839
child process: foo1 is 2, foo2 is 3
parent process: pid is 15839
parent process: foo1 is -1079005816, foo2 is -1218256081
before fork()
child process: pid is 17245, my parent pid is 15839
child process: foo1 is 2, foo2 is 3
parent process: pid is 15839
parent process: foo1 is -1079005816, foo2 is -1218256081
before fork()
.....
.....
If a开发者_如何学Cdd an _exit in the second if block then it'ok. I know the vfork share the same address space with the parent process, but it is more reasonable if the progrem ends with a crash not the endless loop.
vfork
is a very tricky system call and its only intended usage is to immediately have an execve
in the child - for other kinds of uses it is dangerous and unpredictable.
Also note that unlike with fork
, the parent is suspended until the child exits or calls execve
.
from the manual:
the behaviour is undefined if the process created 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.
Because parent and child share the address space, you must not return from the function that called vfork(); doing so can corrupt the parent's stack.
Inside a vfork child you can only call functions safe to call in signal handlers, so printf from inside vfork is a very bad idea.
精彩评论