代码:
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/uio.h>
#include<sys/wait.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
int main()
{
int status;
pid_t pc,pr;
pc=fork(); //创建进程
if(pc<0) //判读进程是否存在
{
perror("creat fork error!\n");
exit(0);
}
if(pc==0) //等于0为子进程
{
printf("there is child pid\n");
printf("the child pid number is:%d\n",getpid()); //获取进程号
sleep(5); //睡眠5秒
exit(4); //退出进程,返回值是4
}
else //否则为父进程
{
printf("there is father pid\n");
printf("the father pid number is:%d\n",getpid()); //获取进程号
do{
pr=waitpid(pc,&status,WNOHANG); //等待子进程(进程同步),获取子进程的返回值并存放在status中
if(pr==0)
{
printf("have not catch the child process\n");
sleep(1);
}
}while(pr==0);
if(pr==pc)
{
printf("catch the chile process\n");
if(WIFEXITED(status)!=0){ //判断子进程是否是正常退出
printf("zheng chang tui chu\n");
printf("fan hui zhi shi:%d\n",WEXITSTATUS(status)); //输出返回值
}else
{printf("bu zheng chang tui chu\n");}
}
}
return 0;
完!!