fork函数介绍
文章目錄
- 1 fork函數(shù)介紹
1 fork函數(shù)介紹
fork函數(shù):
頭文件:
#include <unistd.h>函數(shù)原型:
pid_t fork(void);返回值:
- 成功 :0或其他正整數(shù)
- 失敗:-1
fork函數(shù)特性:
- 執(zhí)行fork函數(shù)之后,fork函數(shù)會(huì)返回兩次
- 在舊進(jìn)程中返回時(shí),返回值為子進(jìn)程的pid
- 在新進(jìn)程返回時(shí),返回值為0
fork函數(shù)要點(diǎn)總結(jié):
- 在執(zhí)行fork函數(shù)之前,操作系統(tǒng)只有一個(gè)進(jìn)程,fork函數(shù)之前的代碼只會(huì)被執(zhí)行一次。
- 在執(zhí)行fork函數(shù)之后,操作系統(tǒng)有兩個(gè)幾乎一樣的進(jìn)程,fork函數(shù)之后的代碼會(huì)被執(zhí)行兩次。
示例代碼:
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main(void) {pid_t result;printf("This is a fork demo!\n\n");/*調(diào)用 fork()函數(shù)*/result = fork();/*通過 result 的值來判斷 fork()函數(shù)的返回情況,首先進(jìn)行出錯(cuò)處理*/if(result == -1) {printf("Fork error\n");}/*返回值為 0 代表子進(jìn)程*/else if (result == 0) {printf("The returned value is %d, In child process!! My PID is %d\n\n", result, getpid());}/*返回值大于 0 代表父進(jìn)程*/else {printf("The returned value is %d, In father process!! My PID is %d\n\n", result, getpid());}return result; }參考資料:
總結(jié)
- 上一篇: 出错处理函数
- 下一篇: bios模式有密码忘记了怎么办 bios