在編寫(xiě)socket ftp之前,我對(duì)fork函數(shù)進(jìn)行了學(xué)習(xí)。
先看這段范例代碼:
#include <unistd.h>;


#include <sys/types.h>;


main ()




{


pid_t pid;


pid=fork();


if (pid < 0)


printf("error in fork!");


else if (pid == 0)


printf("i am the child process, my process id is %dn",getpid());


else


printf("i am the parent process, my process id is %dn",getpid());



}

這段代碼寫(xiě)了一個(gè)使用fork函數(shù)創(chuàng)建子進(jìn)程,父子進(jìn)程同時(shí)運(yùn)行而產(chǎn)生交錯(cuò)的,不一樣的運(yùn)行結(jié)果。
運(yùn)行結(jié)果如下:
[root@localhost c]# ./a.out
i am the child process, my process id is 4286
i am the parent process, my process id is 4285
fork在英文中是叉子,分叉的意思,在函數(shù)fork中,取后面的意思。很形象的表示程序從這里分叉,fork函數(shù)創(chuàng)建了子進(jìn)程,子進(jìn)程和父進(jìn)程同時(shí)(其實(shí)是cpu分時(shí)處理)開(kāi)始運(yùn)行分叉之后的程序。
我把程序改寫(xiě)了一下:
#include <unistd.h>
#include <sys/types.h>
main()


{
pid_t pid;
printf("\n[%d]not fork pid=%d\n",getpid(),pid);
pid=fork();
printf("\n[%d]forked pid=%d\n",getpid(),pid);
if(pid<0)

{
printf("error in fork!\n");
getchar();
exit(1);
}
else if(pid==0)
printf("\n[%d]in child process,p_id=%d\n",getpid(),getpid());
else

{
printf("\n[%d]in parent process,my pid=%d\n",getpid(),pid);
printf("\n[%d]in parent process,my getpid=%d\n",getpid(),getpid());

}
}

程序運(yùn)行結(jié)果如下:
[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]是父進(jìn)程的進(jìn)程號(hào),創(chuàng)建fork以后,fork函數(shù)返回給父進(jìn)程的值pid是子進(jìn)程的進(jìn)程號(hào)[3820],而在子進(jìn)程中,pid值為零。也就是說(shuō)子進(jìn)程中,pid被置零。
引用網(wǎng)上一位網(wǎng)友的解釋“
其實(shí)就相當(dāng)于鏈表,進(jìn)程形成了鏈表,父進(jìn)程pid(p 意味point)指向子進(jìn)程的進(jìn)程id, 因?yàn)樽舆M(jìn)程沒(méi)有子進(jìn)程,所以其pid為0. ”
下面有一個(gè)很有意思的程序:
#include <sys/types.h>
#include <unistd.h>

int main()


{
int i;
for( i= 0; i< 3; i++)

{
int pid= fork();
if(pid== 0)

{
printf("son\n");
}
else

{
printf("father\n");
}
}
return 0;
}

大家想想看最后將出現(xiàn)幾個(gè)son 幾個(gè)father呢?
。
。
。
。
。
。
。
對(duì)一下答案吧:
[hardy@localhost fork]$ ./fork
father
son
son
son
father
father
son
father
son
son
father
father
son
father總共7個(gè)son7個(gè)father。你答對(duì)了么?
這道題需要在紙上畫(huà)畫(huà)才好理解
for i=0 1 2
father father father
son
son father
son
son father father
son
son father
son
其中每一行分別代表一個(gè)進(jìn)程的運(yùn)行打印結(jié)果。
當(dāng)產(chǎn)生子進(jìn)程的時(shí)刻,子進(jìn)程打印son,當(dāng)子進(jìn)程調(diào)用fork的生成子子進(jìn)程,他就提升為father。
總結(jié)來(lái)說(shuō),father永遠(yuǎn)打印father,son在fork之前是son,fork之后就為father,同時(shí)生成新的son。
這個(gè)比喻就像真正的父子,孩子長(zhǎng)大了生了小孩,孩子就成了父親。而父親永遠(yuǎn)是父親。