收集子进程的退出状态
在这之前我们先来了解 fork函数和vfork函数的区别
1、 vfork ()就是能保证子进程先运行,在子进程调用exec 或exit 退出之后父进程才可能被调度运行。如果在调用这两个函数之前子进程依赖于父进程的做进一步动作,则会导致死锁。
2、. fork ():子进程拷贝父进程的数据段,代码段
vfork ( ):子进程与父进程共享数据段
3、 fork ()父子进程的执行次序不确定
vfork 保证子进程先运行,在调用exec 或exit 之前与父进程数据是共享的,在它调用exec
或exit 之后父进程才可能被调度运行。
接下来就是如何收集子进程的退出状态
1、用fork创建进程之后,用wait()函数等待进程退出,wait(NULL)不关心退出状态,
Wait(&status)收集子进程退出状态。
进程正常退出 用宏解析:WEXITSTATUS,收集进程退出状态
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include<stdlib.h>
int main()
{
pid_t pid;
int cnt;
int status=10;
pid=vfork();
if(pid>0)
{
wait(&status);
printf("child quit status=%d\n",WEXITSTATUS(status));
while(1)
{
printf("this is father id:%d\n",getpid());
sleep(2);
printf("cnt=%d\n",cnt);
}
}
else if(pid==0)
{
while(1)
{
printf("this is son id:%d\n",getpid());
sleep(2);
cnt++;
if(cnt==3)
{
exit(3);
}
}
}
return 0;
}
2、Waitpid()非阻塞运行,也就是父子进程一起运行
宏:WNOHANG 不阻塞运行
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include<stdlib.h>
int main()
{
pid_t pid;
int cnt;
int status=10;
pid=fork();
if(pid>0)
{
waitpid(pid,&status,WNOHANG);
printf("child quit status=%d\n",WEXITSTATUS(status));
while(1)
{
printf("this is father id:%d\n",getpid());
sleep(2);
printf("cnt=%d\n",cnt);
}
}
else if(pid==0)
{
while(1)
{
printf("this is son id:%d\n",getpid());
sleep(2);
cnt++;
if(cnt==3)
{
exit(3);
}
}
}
return 0;
}