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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ fork函数理解

發布時間:2023/12/14 c/c++ 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ fork函数理解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

C++的fork函數用來“復制”一份主程序,即創建主進程的子進程。調用fork的同時,我的理解是,已經在內存中創建了“副本”進程,同時返回pid,所以在返回值之前,已經是主進程和子進程同時在運行了(如果fork成功的話),這樣,在程序的運行過程中,一次fork返回了兩次值,在父進程中,fork返回新創建子進程的進程ID,在子進程中,fork返回0,這時候就能夠同時跑兩個進程了。
實列如下:

#include <stdio.h> #include <unistd.h>int main(int argc,char *argv[]){//fork函數使用int i = 0;printf("before fork\n");pid_t pid = fork();printf("after fork\n");if (pid < 0){printf("error\n");return 1;}else if (pid == 0){printf("fork success,this is son process\n");while (i<10){i += 1;printf("this is son process,i=%d\n",i);sleep(1);}}else{printf("fork success,this is father process,son process id is %d \n",pid);while (i<10){i += 2;printf("this is father process,i=%d\n",i);sleep(2);}}return 0; }

運行結果:

before fork after fork fork success,this is father process,son process id is 11054 this is father process,i=2 after fork fork success,this is son process this is son process,i=1 this is son process,i=2 this is father process,i=4 this is son process,i=3 this is son process,i=4 this is father process,i=6 this is son process,i=5 this is son process,i=6 this is father process,i=8 this is son process,i=7 this is son process,i=8 this is father process,i=10 this is son process,i=9 this is son process,i=10

在程序中,我們可以看到,fork函數調用之后,輸出了兩個“after fork”,也就是程序已經存在兩個進程在跑;有一個變量i,在fork之前定義,然后在fork之后的運行過程中,子進程和主進程中的i值互不影響,兩個進程同時在執行,可以驗證fork是將主進程的資源全部拷貝了一份給子進程,兩個進程的資源是獨立的,互不影響。

總結

以上是生活随笔為你收集整理的C++ fork函数理解的全部內容,希望文章能夠幫你解決所遇到的問題。

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