进程fork和vfork的区别

#include <stdio.h>
#include <stdlib.h>
#include <sys/type.h>
int main()
{
	int count = 1;
	int child = fork();
	if(child < 0) {
		perror("fork error");
	}
	else if(child == 0) {
		printf("this is son, %d, %p, pid = %d \n", ++count, &count, getpid());
	}
	else {
		sleep(5);
		printf("this is father, %d, %p, pid = %d \n", count, &count, getpid());
	}
	return 0;
}
---------------------------------------------------
this is son, 2, 0x7ffcc5672338, pid = 13261
this is father, 1 , 0x7ffcc5672338, pid = 13260

fork
父进程和子进程的pid不同,count变量的虚拟地址相同,count的值却不同。
可以得出:堆栈和数据资源都是完全的复制(实际是写时复制),虚拟地址空间相同,但物理地址空间不同。

#include <stdio.h>
#include <stdlib.h>
#include <sys/type.h>
int main()
{
	int count = 1;
	int child = vfork();
	if(child < 0) {
		perror("fork error");
	}
	else if(child == 0) {
		printf("this is son, %d, %p, pid = %d \n", ++count, &count, getpid());
		exit(0);
	}
	else {
		sleep(5);
		printf("this is father, %d, %p, pid = %d \n", count, &count, getpid());
		exit(0);
	}
	return 0;
}
---------------------------------------------------
this is son, 2,     0x7ffcc5672338, pid = 13261
this is father, 2 , 0x7ffcc5672338, pid = 13260

vfork
由vfork创造出来的子进程还会导致父进程挂起,除非子进程exit或者execve才会唤起父进程
由vfok创建出来的子进程共享了父进程的所有内存,包括栈地址,直至子进程使用execve启动新的应用程序为止
由vfork创建出来得子进程不应该使用return返回调用者,或者使用exit()退出,但是它可以使用_exit()函数来退出

总结:
vfork()用法与fork()相似.但是也有区别,具体区别归结为以下3点
fork() 子进程拷贝父进程的数据段,代码段.

vfork() 子进程与父进程共享数据段.|

fork() 父子进程的执行次序不确定.
vfork():保证子进程先运行,

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章