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

请问下面一个关于vfork的c程序的运行结果为什么会出现Segmentation fault ?哪位高手帮我解释下,谢谢。
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>

int main(int argc, char *argv[])
{
  pid_t pid;

  if ((pid = vfork()) < 0)
  printf("fork error\n");
  else if (pid == 0) {
  printf("child, pid = %d\n", getpid());
  sleep(5);
  //exit(1);
  } else {
  printf("parent, pid = %d\n", getpid());
  }

  //printf("hello\n");
printf("hello %d \n",getpid());
}

运行结果:
/* 
[root@localhost testing]# ./vfork_test
child, pid = 4750
hello 4750 
parent, pid = 4749
hello 4749 
Segmentation fault
[root@localhost testing]# 

*/

------解决方案--------------------
vfork不是用来做这事的
说说楼主程序为什么出问题,在vfork中父子进程共享堆栈,因为在子进程中没有调用_exit或是exec,并且子进程先于父进程执行(vfork特性),最后执行了return 0,意思是子进程把父进程的资源给return了,资源销毁了,导致父进程运行环境出问题了,不知道如何return了,找不到回家的路就瞎跑,只能被segment fault了