vfork函数也可以创建进程,与fork不同的是:
1、vfork直接使用父进程存储空间,不拷贝
2、vfork保证子进程先运行,当子进程调用exit退出后,父进程才开始执行。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
int cnt;
pid = vfork();
if(pid > 0){
while(1){
printf("cnt = %d\n",cnt);
printf("this is in father,the father pid = %d\n",getpid());
sleep(2);
}
}else if(pid == 0){
while(1){
printf("this is in chird ,the child pid = %d\n",getpid());
sleep(2);
cnt++;
if(cnt == 5){
exit(0);
}
}
}
return 0;
}
使用vfork函数需要注意的是当父进程开始运行后,子进程会变成僵尸进程。