Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vfork never return

Tags:

c

linux

fork

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.

like image 639
deepsky Avatar asked Apr 23 '26 13:04

deepsky


1 Answers

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.

like image 69
Blagovest Buyukliev Avatar answered Apr 26 '26 04:04

Blagovest Buyukliev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!