vfork函数 也可以创建进程,与fork有什么区别
关键区别一: vfork 直接使用父进程存储空间,不拷贝。
关键区别二: vfork保证子进程先运行,当子进程调用exit退出后,父进程才执行。
fork创建
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid = fork();
if(pid > 0){
while(1){
printf("father print , pid = %d\n",getpid());
sleep(1);
}
}else if(pid == 0){
while(1){
printf("son print , pid = %d\n",getpid());
sleep(1);
}
}
return 0;
}
father print , pid = 28837
son print , pid = 28838
son print , pid = 28838
father print , pid = 28837
father print , pid = 28837
son print , pid = 28838
son print , pid = 28838
father print , pid = 28837
father print , pid = 28837
son print , pid = 28838
结果:父进程和子进程都在运行,先运行那个看进程调度
vfork创建
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid = vfork();
if(pid > 0){
while(1){
printf("father print , pid = %d\n",getpid());
sleep(1);
}
}else if(pid == 0){
while(1){
printf("son print , pid = %d\n",getpid());
sleep(1);
}
}
return 0;
}
son print , pid = 28882
son print , pid = 28882
son print , pid = 28882
son print , pid = 28882
son print , pid = 28882
son print , pid = 28882
结果:用vfrok创建只有子进程在运行
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int cnt = 0;
pid = vfork();
if(pid > 0){
while(1){
printf("father print , pid = %d\n",getpid());
printf("cnt = %d\n",cnt);
sleep(1);
}
}else if(pid == 0){
while(1){
printf("son print , pid = %d\n",getpid());
sleep(1);
cnt++;
if(cnt == 5){
exit(0);
}
}
}
return 0;
}
son print , pid = 28983
son print , pid = 28983
son print , pid = 28983
son print , pid = 28983
son print , pid = 28983
father print , pid = 28982
cnt = 5
father print , pid = 28982
cnt = 5
father print , pid = 28982
cnt = 5