进程的退出
void exit(int status);
其中staus代表进程的退出状态
僵尸进程
进程在结束的时候,不管是异常退出还是正常退出,还是exit
或是return
终止进程,进程所占用的内存资源都会被操作系统回收,成不了zombie
,而子进程在使用exit
、_exit
、return
退出的时候,只是灵魂性的退出,而肉体并没有退出,那么我们如何把内核中的肉体,也就是内核中task_struct
结构体清掉呢?
进程的肉体也叫僵尸进程,那么父进程就要使用wait
和waitpid
函数进行清除内核中的task_struct
结构体。zombie
的作用是维护子程序的信息,以便父程序在以后能够调用它。这些信息包括:进行ID,终止状态、资源利用率(CPU利用率、内存使用等等)。但是操作系统限制了某一时刻能同时存在的进程的最大数目,虽然说它们不占有CPU,不占有内存,但是当下次产生新进程的时候,就会产生未知的错误。因此,有效的处理僵死进程,是有必要的一些事。这个时候,就用到了wait
和waitpid
两个函数。
父进程回收子进程
pid_t wait(int * wstatus);
pid_t waitpid(pid_t pid,int *wstatus,int options);
对于wait来说会阻塞,直到子进程结束
waitpid 的返回值是: 退出的子进程的pid
wstatus: 子进程的退出码(也就是子进程中exit括号中填的参数)
options: 表示阻塞或非阻塞(阻塞:填0 非阻塞:WNOHANG)
pid_t pid:
- pid>0 : 指定等待哪个子进程
- pid=-1 :表示等待任意子进程结束
- pid = 0 : 表示等待与当前进程的gpid相同的任意一个进程结束
- pid< -1 : (例如:-2)等待组ID为2的任意一个子进程
wait DEMO
#include <sys/types.h>
#include <unistd.h>
#include "stdio.h"
#include "stdlib.h"
int main()
{
pid_t pid;
int cnt=0;
int status=0;
pid=fork();
if(pid>0)
{
wait(&status);
printf("child quit,child status = %d\n",WEXITSTATUS(status));//检查wait返回的终止状态的宏定义 status需用宏解析才能得到返回值
while(1){
printf("cnt=%d\n",cnt);
printf("this is father printf,pid=%d\n",getpid());
sleep(1);
}
}else if(pid == 0){
while(1){
printf("this is son pid=%d\n",getpid());
sleep(1);
cnt++;
if(cnt==3) exit(3);
}
}
return 0;
}
执行结果
CLC@Embed_Learn:~/xiaoma$ ./a.out
this is son pid=31166
this is son pid=31166
this is son pid=31166
child quit,child status = 3
cnt=0
this is father printf,pid=31165
cnt=0
this is father printf,pid=31165
cnt=0
this is father printf,pid=31165
cnt=0
this is father printf,pid=31165
^C
CLC@Embed_Learn:~/xiaoma$
waitpid DEMO
#include <sys/types.h>
#include <unistd.h>
#include "stdio.h"
#include "stdlib.h"
int main()
{
pid_t pid;
int cnt=0;
int status=0;
pid=fork();
if(pid>0)
{
waitpid(pid,&status,WNOHANG);
printf("child quit,child status = %d\n",WEXITSTATUS(status));
while(1){
printf("cnt=%d\n",cnt);
printf("this is father printf,pid=%d\n",getpid());
sleep(1);
}
}else if(pid == 0){
while(1){
printf("this is son pid=%d\n",getpid());
sleep(1);
cnt++;
if(cnt==3) exit(3);
}
}
return 0;
}
执行结果
child quit,child status = 0
cnt=0
this is father printf,pid=31231
this is son pid=31232
cnt=0
this is son pid=31232
this is father printf,pid=31231
cnt=0
this is son pid=31232
this is father printf,pid=31231
cnt=0
^C
注意的是waitpid
在不阻塞的情况在子进程也会变成僵尸进程
孤儿进程
父进程如果不等待子进程退出,在子进程之前就结束了自己的“生命”,此时子进程叫做孤儿进程
Linux避免系统存在过多孤儿进程,init进程收留孤儿进程,变成孤儿进程的父进程getppid()
查后来父进程ID