日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

Linux fork函数

發(fā)布時間:2023/12/14 linux 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Linux fork函数 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。