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 add 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.
vforkis a very tricky system call and its only intended usage is to immediately have anexecvein 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 callsexecve.