vfork()与fork()区别

fork函数创建子进程后,父子进程是独立、同时运行得,而且没有先后顺序
vfork()产生的父子进程,一定是子进程先运行完,再运行父进程

直接上代码

fork()

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>

int main(void)
{
	pid_t child;

	/* 创建子进程 */
	if((child=fork())==-1)
	{
		printf("Fork Error : %s\n", strerror(errno));
		exit(1);
	}
	else 
		if(child==0) // 子进程
		{
			printf("I am the child_pid: %d\n", getpid());
			exit(0);
		}
		else        //父进程
		{
			printf("I am the father_pid:%d\n",getpid());
			return 0;
		}
}	

打印结果:在这里插入图片描述
父子进程无顺序运行

vfork()

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>

int main(void)
{
	pid_t child;

	/* 创建子进程 */
	if((child=vfork())==-1)
	{
		printf("Fork Error : %s\n", strerror(errno));
		exit(1);
	}
	else 
		if(child==0) // 子进程
		{
			sleep(2); //子进程睡眠2秒
			printf("I am the child: %d\n", getpid());
			exit(0);
		}
		else        //父进程
		{
			printf("I am the father:%d\n",getpid());
			exit(0);
		}
}	

结果:
在这里插入图片描述
图中 运行结果 8256的进程是2秒后出现,随后出现8255。

总结 调用fork函数产生的父子进程运行顺序不定,而调用vfork函数,是先子后父。

发布了14 篇原创文章 · 获赞 23 · 访问量 3293

猜你喜欢

转载自blog.csdn.net/sf9090/article/details/103082753
今日推荐