Linux fork()詳解:
在開始之前,我們先來了解一些基本的概念:
1. 程序, 沒有在運行的可執行文件
進程, 運行中的程序
2. 進程調度的方法:
按時間片輪轉
先來先服務
短時間優先
按優先級別
3. 進程的狀態:
就緒 ->> 運行 ->> 等待
運行 ->> 就緒 //時間片完了
等待 ->> 就緒 //等待的條件完成了
查看當前系統進程的狀態 ps auxf
status:
D Uninterruptible sleep (usually IO)
R Running or runnable (on run queue)
S Interruptible sleep (waiting for an event to complete)
T Stopped, either by a job control signal or because it is being traced.
W paging (not valid since the 2.6.xx kernel)
X dead (should never be seen)
Z Defunct ("zombie") process, terminated but not reaped by its parent.
< high-priority (not nice to other users)
N low-priority (nice to other users)
L has pages locked into memory (for real-time and custom IO)
s is a session leader
l is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)
+ is in the foreground process group
4. 父進程/子進程 , 讓一個程序運行起來的進程就叫父進程, 被調用的進程叫子進程
5. getpid //獲取當前進程的進程號
getppid //獲取當前進程的父進程號
6. fork //創建一個子進程,創建出來的子進程是父進程的一個副本, 除了進程號,父進程號不同。
子進程從fork()后開始運行, 它得到的fork返回值為0
父進程得到的返回值為子進程的進程號
返回值為-1時, 創建失敗
來看一個程序:
#include <stdio.h> #include <unistd.h> int main(void) { pid_t pid ; //printf("hello world /n"); //從fork開始就已經產生子進程 pid = fork(); //就已經產生新的4G空間,復制空間 //創建出來的子進程是父進程的一個副本,除了進程號,父進程號和子進程號不同 //printf("hello kitty/n"); if(pid == 0) { //子進程運行區 printf("child curpid:%d parentpid:%d /n" , getpid() , getppid()); return 0 ; } //父進程運行區 printf("parent curpid:%d parentpid:%d /n" , getpid() , getppid()); return 0 ; }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答