社區(qū)工作者優(yōu)化設(shè)計(jì)方法
函數(shù)原型
pid_t vfork(void);//pid_t是無(wú)符號(hào)整型
所需頭文件
#include <sys/types.h>
#include <unistd.h>
功能
vfork() 函數(shù)和 fork() 函數(shù)一樣都是在已有的進(jìn)程中創(chuàng)建一個(gè)新的進(jìn)程,但它們創(chuàng)建的子進(jìn)程是有區(qū)別的。
返回值
成功 | 子進(jìn)程中返回 0,父進(jìn)程中返回子進(jìn)程 ID |
失敗 | 返回 -1 |
vfork與fork的區(qū)別
關(guān)鍵區(qū)別一:
fork執(zhí)行時(shí)無(wú)先后順序,父進(jìn)程與子進(jìn)程會(huì)爭(zhēng)奪執(zhí)行?
vfork保證子進(jìn)程先運(yùn)行,當(dāng)子進(jìn)程調(diào)用exit退出后,父進(jìn)程才執(zhí)行
代碼驗(yàn)證
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>int main()
{int fork_t = 0;fork_t = fork();if(fork_t > 0){while(1) {printf("This is father\n");sleep(1);}}else if(fork_t == 0){while(1){printf("This is child\n");sleep(1);}}return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>int main()
{int vfork_t = 0;int count = 0;vfork_t = vfork();if(vfork_t > 0){while(1) {printf("This is father\n");sleep(1);}}else if(vfork_t == 0){while(1){printf("This is child\n");sleep(1);count++;if(count >= 3){exit(-1);//輸出三次子進(jìn)程,之后退出}}}return 0;
}
第一部分代碼可見(jiàn)fork函數(shù)中的父進(jìn)程和子進(jìn)程會(huì)爭(zhēng)奪輸出,而第二部分的vfork函數(shù)會(huì)在子進(jìn)程輸出3次退出之后再執(zhí)行父進(jìn)程。
關(guān)鍵區(qū)別二:
fork中子進(jìn)程會(huì)拷貝父進(jìn)程的所有數(shù)據(jù),子進(jìn)程是父進(jìn)程的地址空間
vfork中子進(jìn)程共享父進(jìn)程的地址空間
代碼驗(yàn)證
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>int main()
{int fork_t = 0;int a = 10;fork_t = fork();if(fork_t != 0){printf("This is father,a = %d\n",a);}else{printf("This is child,a = %d\n",a);}return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>int main()
{int vfork_t = 0;int count = 0;vfork_t = vfork();if(vfork_t > 0){while(1) { printf("count = %d\n",count);printf("This is father\n");sleep(1);}}else if(vfork_t == 0){while(1){printf("This is child\n");sleep(1);count++;if(count >= 3){exit(0);}}}return 0;
}
第一部分代碼可知,在父進(jìn)程中定義a,調(diào)用fork函數(shù)時(shí),父進(jìn)程與子進(jìn)程打印a的值一樣,說(shuō)明子進(jìn)程會(huì)拷貝父進(jìn)程的所有數(shù)據(jù)(父進(jìn)程的只打印自己的值,不會(huì)收子進(jìn)程影響);第二部分代碼可知,在子進(jìn)程結(jié)束之后,才會(huì)執(zhí)行父進(jìn)程,且子進(jìn)程中數(shù)值發(fā)生改變,在父進(jìn)程調(diào)用時(shí)會(huì)發(fā)生改變(一開(kāi)始父進(jìn)程a=0,調(diào)用后a=3),會(huì)受到子進(jìn)程影響