linux fork函式學習

2021-08-30 16:15:15 字數 1763 閱讀 7863

在編寫socket ftp之前,我對fork函式進行了學習。

先看這段範例**:

#include ;

#include ;

main ()

這段**寫了乙個使用fork函式建立子程序,父子程序同時執行而產生交錯的,不一樣的執行結果。

執行結果如下:

# ./a.out

i am the child process, my process id is 4286

i am the parent process, my process id is 4285

fork在英文中是叉子,分叉的意思,在函式fork中,取後面的意思。很形象的表示程式從這裡分叉,fork函式建立了子程序,子程序和父程序同時(其實是cpu分時處理)開始執行分叉之後的程式。

我把程式改寫了一下:

#include

#include

main()

else if(pid==0)

printf("\n[%d]in child process,p_id=%d\n",getpid(),getpid());

else

}程式執行結果如下:

[hardy@localhost fork]$ ./fork

[3819]not fork

[3820]forked pid=0

[3820]in child process,p_id=3820

[3819]forked pid=3820

[3819]in parent process,my pid=3820

[3819]in parent process,my getpid=3819

可以清楚的看到 not fork只列印了一次,其中[3819]是父程序的程序號,建立fork以後,fork函式返回給父程序的值pid是子程序的程序號[3820],而在子程序中,pid值為零。也就是說子程序中,pid被置零。

引用網上一位網友的解釋「其實就相當於鍊錶,程序形成了鍊錶,父程序pid(p 意味point)指向子程序的程序id, 因為子程序沒有子程序,所以其pid為0. 」

下面有乙個很有意思的程式:

#include

#include

int main()

else

}return 0;

}大家想想看最後將出現幾個son 幾個father呢?。。

。。。。

。對一下答案吧:

[hardy@localhost fork]$ ./fork

father

sonson

sonfather

father

sonfather

sonson

father

father

sonfather

總共7個son7個father。你答對了麼?

這道題需要在紙上畫畫才好理解

for i=0 1 2

father father father

sonson father

sonson father father

sonson father

son其中每一行分別代表乙個程序的執行列印結果。

當產生子程序的時刻,子程序列印son,當子程序呼叫fork的生成子子程序,他就提公升為father。

總結來說,father永遠列印father,son在fork之前是son,fork之後就為father,同時生成新的son。

這個比喻就像真正的父子,孩子長大了生了小孩,孩子就成了父親。而父親永遠是父親。

linux fork 函式學習

分類 專業學習 include include include int main case 0 default printf n d n n return 0 輸出結果1 fork child i am child parent i am parent parent getpid 4496 pare...

linux fork函式與vfork函式

一 fork 1.呼叫方法 include include pid t fork void 正確返回 在父程序中返回子程序的程序號,在子程序中返回0 錯誤返回 1 子程序是父程序的乙個拷貝。即,子程序從父程序得到了資料段和堆疊段的拷貝,這些需要分配新的記憶體 而對於唯讀的 段,通常使用共享記憶體的方...

linux fork函式的精闢解說

開始演示 plain view plaincopyprint?root test code cat fork.c include include include main root test code gcc fork.c o fork root test code fork i am the ch...