天天看點

linux下的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;
		}
}	

           

列印結果:

linux下的vfork()與fork()兩個函數的差別,使用方法

父子程序無順序運作

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);
		}
}	

           

結果:

linux下的vfork()與fork()兩個函數的差別,使用方法

圖中 運作結果 8256的程序是2秒後出現,随後出現8255。

總結 調用fork函數産生的父子程序運作順序不定,而調用vfork函數,是先子後父。

繼續閱讀