#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():保證子進程先運行,