隨着一句fork,一個新進程“呱呱墜地”,但這時它只是老進程的一個“克隆”。隨後,隨着exec,新進程脫胎換骨,離家獨立,開始了獨立工作的職業生涯。
人有生老病死,進程也一樣。它可能是自然死亡,即運行到main函數的最後一個“}”,從容地離去;也可能是中途退場,退場有兩種方式,一種是調用exit函數,一種是在main函數內使用return,無論哪一種方式,它都可以留下留言,放在返回值裏保留下來;它甚至還可能被謀殺,即被其他進程通過另外一些方式結束它的生命。
進程死亡以後會留下一個空殼,wait站好最後一班崗,打掃戰場,使其最終歸於無形。這就是進程完整的一生。
#include <sys/types.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
main()
{
pid_t p,pc;
p=fork();
if(p<0){
printf("error\n");
}
else if(p==0){
printf("this is child process with pid of %d\n",getpid());
sleep(5);
}
else{
pc=wait(NULL);
printf("this is father process with pid of %d and I catched a child process with pid of %d\n",getpid(),pc);
}
exit(0);
}
[huazi@huazi c]$ ./fork
this is child process with pid of 12939
this is father process with pid of 12938 and I catched a child process with pid of 12939
[huazi@huazi c]$