随着一句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]$