日期:2014-05-16  浏览次数:20556 次

vfork函数
程序1:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int g_a = 1;

int main(void){
        int l_b = 1;
        pid_t p;
        if((p = vfork()) < 0){
                perror("fork");
        }else if(p == 0){
                g_a++;
                l_b++;
        }
        printf("ppid = %d,pid = %d,g_a = %d,l_b = %d\n", getppid(), getpid(), g_a, l_b);
        return 0;
}

代码执行时出现段错误:
yan@yan-vm:~/apue$ ./a.out
ppid = 4101,pid = 4102,g_a = 2,l_b = 2
ppid = 3791,pid = 4101,g_a = 2,l_b = 1
Segmentation fault (core dumped)

如果在子进程中加入exit或者_exit函数后就能成功运行。
程序2:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int g_a = 1;

int main(void){
        int l_b = 1;
        pid_t p;
        if((p = vfork()) < 0){
                perror("fork");
        }else if(p == 0){
                g_a++;
                l_b++;
                exit(0);
        }
        printf("ppid = %d,pid = %d,g_a = %d,l_b = %d\n", getppid(), getpid(), g_a, l_b);
        return 0;
}

yan@yan-vm:~/apue$ ./a.out
ppid = 3791,pid = 4115,g_a = 2,l_b = 2

在程序1中子进程最后执行了return 0,在程序2中子进程最后执行了exit(0),这两个语句的效果不应该是一样的么?如果不一样,区别是什么?

------解决方案--------------------
其实fork用return也会产生灾难性的问题。其实只要是fork,vfork之类的,就要用exit退出,而不是return.
------解决方案--------------------
直接exit吧! 估计是栈被破坏了!return只是函数返回而已!