vfork 例子祥解
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
printf("Start ..............\n");
pid_t child_t;
if((child_t = vfork()) < 0)
{
printf("error!\n");
return -1;
}
else if(child_t == 0)
{
printf("in child:pid =%d\n",getpid());
sleep(2);
_exit(0); //必须退出子进程。否则子进程会运行到printf("End ............... \n");return 0;然后退出子进程,把共父子进程共享的栈空间释放了,父进程就陷入了死循环。看下面的gdb调试。
}
else
{
printf("in parent:child_t id = %d,pid = %d\n",child_t,getpid());
}
printf("End ............... \n");
return 0;
}
屏蔽_exit(0);后的gdb调试信息:
Breakpoint 1, main (argc=1, argv=0xbffff954) at main.cpp:9
9 printf("Start ..............\n");
(gdb) c
Continuing.
Start .............. //开始运行
in child:pid =25272 //分裂出子进程
End ............... //子进程,退出。
Breakpoint 3, main (argc=0, argv=0xbffff954) at main.cpp:24 //子过程完成后才会运行父进程,argc=0,说明栈空间已被释放
24 printf("in parent:child_t id = %d,pid = %d\n",child_t,getpid());//父进程。
(gdb) c
Continuing.
in parent:child_t id = 25272,pid = 25269
Breakpoint 4, main (argc=0, argv=0xbffff954) at main.cpp:26
26 printf("End ............... \n");
(gdb) c
Continuing.
End ............... //父进程,退出。因为argc=0,但argv[0_tes]="/work/test/smallt/test.i386.elf"还是存在,所以又开始运行。所以进入了死循环了。
Breakpoint 1, main (argc=1, argv=0xbffff954) at main.cpp:9
9 printf("Start ..............\n");//又开始运行了。
(gdb) p argv[0]
$1 = 0xbffffacd "/work/test/small_test/test.i386.elf"
(gdb)