创建进程相关函数
fork函數(shù)
pid_t fork(void); fork函數(shù)調(diào)用成功, 返回兩次 在fork函數(shù)執(zhí)行完畢后 如果創(chuàng)建新進(jìn)程成功,則出現(xiàn)兩個進(jìn)程 一個是子進(jìn)程,一個是父進(jìn)程 在子進(jìn)程中,fork函數(shù)返回0 在父進(jìn)程中,fork返回新創(chuàng)建子進(jìn)程的進(jìn)程ID 我們可以通過fork返回的值來判斷當(dāng)前進(jìn)程是子進(jìn)程還是父進(jìn)程。?返回值為0,代表當(dāng)前進(jìn)程是子進(jìn)程
?返回值是非負(fù)數(shù),代表當(dāng)前進(jìn)程為父進(jìn)程
?調(diào)用失敗,返回-1
?返回值是pid_t 類型的,這里的pid_t類似一個類型,就像int型一樣,int型定義的變量都是整型的,pid_t定義的類型都是進(jìn)程號類型。這個語句的意思是定義了一個pid_t類型的變量pid,fork()函數(shù)返回一個進(jìn)程號,這個進(jìn)程號賦給了pid。
代碼示例
#include<stdio.h> #include <sys/types.h> #include <unistd.h> int main() {pid_t pid;pid_t fpid;printf("father id :%d\n",getpid());fpid=fork();if(fpid>0){printf("this is father print,pid=%d\n",getpid());}else if(pid==0){printf("this is child print,pid=%d\n",getpid());}return 0; } 運(yùn)行結(jié)果:father id :17615this is father print,pid=17615this is child print,pid=17616判斷進(jìn)程的運(yùn)行順序
#include<stdio.h> #include <sys/types.h> #include <unistd.h> int main() {pid_t pid;pid_t fpid;pid_t returnpid;printf("father id :%d\n",getpid());returnpid=fork();fpid=getpid();//獲取當(dāng)前進(jìn)程的pid,父子進(jìn)程都會執(zhí)行這句話getppid()——獲取父進(jìn)程的pidif(fpid==pid){printf("this is father print,pid=%d,returnpid=%d\n",getpid(),returnpid);}else{printf("this is child print,pid=%d,returnpid=%d\n",getpid(),returnpid);}return 0; } 運(yùn)行結(jié)果:father id :17638this is child print,pid=17638,returnpid=17639this is child print,pid=17639,returnpid=0子進(jìn)程改變變量父進(jìn)程中的變量不變
#include<stdio.h> #include <sys/types.h> #include <unistd.h> int main() {pid_t pid;pid_t fpid;int a=10;printf("father id :%d\n",getpid());fpid=fork();if(fpid>0){printf("this is father print,pid=%d\n",getpid());}else if(pid==0){printf("this is child print,pid=%d\n",getpid());a=a+10;}printf("a=%d\n",a);return 0; } 運(yùn)行結(jié)果: father id :17660this is father print,pid=17660a=10this is child print,pid=17661a=20創(chuàng)建子進(jìn)程的目的
模擬與客戶端交互
vfork函數(shù)
pid_t vfork(void); 用法和fork函數(shù)一樣
代碼示例
總結(jié)
- 上一篇: 第四十九期:化繁为简的五种码农必备工具
- 下一篇: com.autonavi.amap.ma