Linux fork函数
1、fork函數(shù)用于創(chuàng)建子進程,其特殊性在于調用一次fork函數(shù),會得到兩次返回值:
? ? 1)在父進程中,fork返回新創(chuàng)建子進程的進程ID;
????2)在子進程中,fork返回0;
????3)如果出現(xiàn)錯誤,fork返回一個負值;
簡單示例:
#include "stdio.h" #include "stdlib.h" #include "unistd.h" #include <iostream> using namespace std;int main(int argc, char **argv) {pid_t pid;cout << "begin process..." << endl;pid = fork();if (pid == -1){cout << "fork error." << endl;exit(1);}else if (pid == 0){cout << "Im a child,pid = " << getpid() << ",ppid = " << getppid() << endl;}else{cout << "Im a parent,pid = " << getpid() << ",ppid = " << getppid() << endl;//延時,保證父進程后退出sleep(1);}cout << "end process..." << endl; }運行結果:
?2、簡單示例,創(chuàng)建5個子進程:
#include "stdio.h" #include "stdlib.h" #include "unistd.h" #include <iostream> using namespace std;int main(int argc, char **argv) {int i;pid_t pid;cout << "begin process..." << endl;for (i = 0; i < 5; ++i){pid = fork();if (pid == 0) //子進程{break;}}sleep(i);if (i < 5){cout << "我是第 " << i + 1 << " 個子進程,pid = " << getpid() << endl;}else{cout << "我是父進程" << endl;}cout << "end process..." << endl;return 0; }?3、父子進程共享機制:讀時共享,寫時復制。
4、fork函數(shù)的作用,來自別處作為參考:
當你要創(chuàng)建一個子進程的時候就用fork()函數(shù),它一般有兩種應用,
第一,創(chuàng)建一個子進程用來執(zhí)行和父進程不同的代碼段,這個在網(wǎng)絡中應用比較廣,比如服務器端fork一個子進程用來等待客戶端的請求,當請求到來時,子進程響應這個請求,而父進程則繼續(xù)等待客戶端請求的到來;
第二,創(chuàng)建一個子進程用來執(zhí)行和父進程不同的程序,這種應用往往 fork一個子進程之后立即調用exec族函數(shù),exec族函數(shù)則調用新的程序來代替新創(chuàng)建的子進程。
5、讓子進程調用一個程序執(zhí)行其它操作:
此處使用exec函數(shù)族中的函數(shù):execlp和execl,函數(shù)只在執(zhí)行錯誤的時候返回。
execlp:在環(huán)境變量所指的目錄中查找參數(shù)file所指的文件(可執(zhí)行程序);
execl:在path字符串所指的目錄中查找可執(zhí)行程序;
int execl(const char *path, const char *arg, .../* (char *) NULL */); int execlp(const char *file, const char *arg, .../* (char *) NULL */);?簡單示例:
#include "stdlib.h" #include "unistd.h" #include <iostream> using namespace std;int main(int argc, char **argv) {pid_t pid;pid = fork();if (pid == -1){cout << "fork error." << endl;exit(1);}else if (pid == 0){cout << "Im a child,pid = " << getpid() << ",ppid = " << getppid() << endl;//調用一個新進程來代替子進程execlp("ls", "ls", "-l", NULL);//如果執(zhí)行失敗,才能執(zhí)行到此處:結束子進程exit(0);}else{cout << "Im a parent,pid = " << getpid() << ",ppid = " << getppid() << endl;//延時,保證父進程后退出sleep(1);}return 0; }?
總結
以上是生活随笔為你收集整理的Linux fork函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: fork()函数详解
- 下一篇: 对计算机态度英语作文,对自动化的看法英语