vfork()

函数原型

pid_t vfork(void);//pid_t是无符号整型

所需头文件

#include 

#include 

功能

vfork() 函数和 fork() 函数一样都是在已有的进程中创建一个新的进程,但它们创建的子进程是有区别的。

返回值

成功子进程中返回 0,父进程中返回子进程 ID
失败返回 -1

vfork与fork的区别

关键区别一:

fork执行时无先后顺序,父进程与子进程会争夺执行 

vfork保证子进程先运行,当子进程调用exit退出后,父进程才执行

#include 
#include 
#include 

int main()
{

       pid_t pid;

       pid = fork();//vfork()
       
      if(pid > 0)
       {
	       while(1)
	       {
		       printf("this is father
");
		       sleep(1);
	       }       		
       }
      else if(pid == 0)
       {
	       while(1)
	       {
		       printf("this is child
");
		       sleep(1);
	       }
       }

	return 0;

}

当调用fork()时:父进程和子进程会争夺输出Linux进程——vfork函数插图

当调用vfork()时:由于当子进程调用exit退出后,父进程才执行。子进程未调用exit,故父进程为执行。

Linux进程——vfork函数插图(1)

#include 
#include 
#include 
#include 
 
int main()
{
	int pid = 0;
	int count = 0;
 
	pid = vfork();
 
	if(pid > 0)
	{
		while(1)		
		{
			printf("This is father
");
			sleep(1);
		}
	}
	else if(pid == 0)
	{
		while(1)
		{
			printf("This is child
");
			sleep(1);
			count++;
			if(count >= 3)
			{
				exit(-1);//输出三次子进程,之后退出
			}
		}
				
	}
	return 0;
}

 Linux进程——vfork函数插图(2)

子进程输出3次退出之后再执行父进程。


关键区别二:

fork中子进程会拷贝父进程的所有数据,子进程是父进程的地址空间

vfork中子进程共享父进程的地址空间

#include 
#include 
#include 
#include 
int main()
{
	int count = 0;
       pid_t pid;

       pid = vfork();//fork()
       

      if(pid > 0)
       {
	       while(1)
	       {
		       printf("this is father
");
		       sleep(1);
		       printf("count == %d
",count);
	       }       		
       }
      else if(pid == 0)
       {
	       while(1)
	       {
		       printf("this is child
");
		       sleep(1);
		       count++;
		       if(count >= 3)
		       {
			       exit(-1);
		       }
	       }
       }

	return 0;

}

 若调用fork(),则父子进程的变量是子进程copy父进程的,即父进程的count为0,此时的子进程计算完的count未与父进程共享地址;

若调用vfork(),子进程共享父进程的地址空间,即子进程计算完count的值又传回给了父进程,count就为3

Linux进程——vfork函数插图(3)

本站无任何商业行为
个人在线分享 » Linux进程——vfork函数
E-->