Linux vfork()

DXT00發表於2019-03-16

轉自:https://blog.csdn.net/jianchi88/article/details/6985326

1.vfork()建立子程式,在呼叫exec()之前或exit()之前,子程式與父程式共享資料段(與fork()不同,fork要拷貝父程式的資料段,堆疊段)

2.呼叫vfork()後,子程式先執行,父程式被掛起,直到子程式呼叫了exec或exit之後,父程式才執行。

 

例子1:

fork()

#include <unistd.h>
#include <stdio.h>

int main(int argc, char const *argv[])
{
	int cnt = 1;

	pid_t pid = fork();

	if(pid<0){
		printf("process error!!\n");
		return 1;
	}
	else if(pid==0){
		printf("this is a child process, id = %d, count =%d \n",getpid(),cnt++);
	}
	else
		printf("this is the parent process, id = %d, count =%d \n",getpid(),cnt++);

	return 0;
}

子程式拷貝父程式的資料段,堆疊段。處於不同的記憶體位置,所以cnt都是1

輸出:

this is the parent process, id = 2661, count =1 
this is a child process, id = 2664, count =1 

 

 例子2:

使用vfork(),但子程式不呼叫exit()或exec(),父程式一直掛起

導致死鎖!

#include <unistd.h>
#include <stdio.h>

int main(int argc, char const *argv[])
{
	int cnt = 1;

	pid_t pid = vfork();

	if(pid<0){
		printf("process error!!\n");
		return 1;
	}
	else if(pid==0){
		printf("this is a child process, id = %d, count =%d \n",getpid(),cnt++);
	}
	else
		printf("this is the parent process, id = %d, count =%d \n",getpid(),cnt++);

	return 0;
}

輸出:

this is a child process, id = 3248, count =1 
this is the parent process, id = 3247, count =4195584 
vfork: cxa_atexit.c:100: __new_exitfn: Assertion `l != NULL' failed.
已放棄 (核心已轉儲)

例子3:

使用vfork(),並且子程式呼叫exit()或exec()

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
	int cnt = 1;

	pid_t pid = vfork();

	if(pid<0){
		printf("process error!!\n");
		return 1;
	}
	else if(pid==0){
		printf("this is a child process, id = %d, count =%d \n",getpid(),cnt++);
		exit(1);
	}
	else
		printf("this is the parent process, id = %d, count =%d \n",getpid(),cnt++);

	return 0;
}

子程式執行exit(1)退出後,父程式開始執行,由於共享資料段,所以cnt在子程式加1的基礎上再加1 =2

this is a child process, id = 3497, count =1 
this is the parent process, id = 3496, count =2 

相關文章