Linux高階程式設計基礎——程序之 fork 與 vfork 使用
阿新 • • 發佈:2018-11-10
程序之 fork 與 vfork 使用
編寫程式實現以下功能:
- 在父程序中定義變數n,在子程序中對變數n進行++操作;並且列印變數n的值,列印子程序pid;
- 在父程序中列印變數n的值,並且列印父程序pid。
- 要求分別用fork和vfork建立子程序。
#include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> int main() { int n=1; pid_t pid=fork(); //使用fork 建立子程序,得到一個返回值(pid),通過這個返回值可以判斷一個程序是 子程序 還是 父程序 if(pid == 0) //pid 為0 時,是子程序 { n++; printf("fork出的子程序中n=%d\n",n); //列印子程序中 n++的結果 exit(0); } else{ sleep(1); printf("父程序中n=%d\n",n); //列印父程序中 n的結果 printf("fork出的子程序為pid:%d\n",pid);//這個返回值(pid)在父程序中返回的是 子程序的 ID printf("父程序的pid:%d\n",getpid()); //列印父程序的 ID pid_t pid1=vfork();//使用 vfork 建立子程序,得到一個返回值( pid1 ) if(pid1 == 0) //pid 為0 時,是子程序 { sleep(2); n++; printf("vfork 出的子程序中n=%d\n",n); //列印子程序中 n++的結果 exit(0); } else { printf("父程序中n=%d\n",n); //列印父程序中 n的結果 printf("pid1:%d\n",pid1); printf("父程序的pid:%d\n",getpid()); } } return 0; }
/*
- fork出來的子程序列印的 n 於 父程序列印的 n 的值一樣嗎?
不一樣 ,因為fork建立的子程序是完全複製父程序的資源,之後獨立於父程序之外 - vfork出來的子程序列印的 n 於 父程序列印的 n 的值一樣嗎?
一樣 ,vfork函式並不將父程序的地址空間完全複製到子程序中。而是與父程序共享資源 - vfork 於 fork 區別 ?
回答就是前兩個問題的答案
*/