僵尸进程
子进程状态不被收集的话,这个进程就变成僵尸进程,
父进程等待子进程退出,并收集子进程的退出状态。
#include <sys/types.h>
#include <sys/wait.h>
//函数原型
pid_t wait(int *status);
/*
status参数
是一个整数型指针
非空:子进程退出状态放在它的地址中
空:不关心退出状态
**********************************************
**wait(NULL)后子进程结束后就消失不会变成僵尸进程**
*/
在父进程前面加入wait(NULL); 就会得到子进程的退出状态不变成僵尸进程
运行结果 没有使用wait和使用wait(NULL) ;
sp@sp-virtual-machine:~/jieduan2/jincheng$ ps -aux|grep a.out
sp 29972 0.0 0.0 4512 1288 pts/1 S+ 16:36 0:00 ./a.out
sp 29973 0.0 0.0 0 0 pts/1 Z+ 16:36 0:00 [a.out] <defunct>
sp 29976 0.0 0.0 16184 1076 pts/0 S+ 16:36 0:00 grep --color=auto a.out
sp@sp-virtual-machine:~/jieduan2/jincheng$ ps -aux|grep a.out
sp 30084 0.0 0.0 4512 1192 pts/1 S+ 16:44 0:00 ./a.out
sp 30087 0.0 0.0 16184 1092 pts/0 S+ 16:44 0:00 grep --color=auto a.out
wait的宏定义
使用方法
如果子进程在运行,则实行阻塞
int status;
//在父进程里面使用wait函数
pid_t pid;
int cnt=0;
int status=10;
if(deta==1){
pid=vfork();
if(pid>0){
wait(&status);//等待子进程,实行阻塞
//打印出来真正的退出需要用宏定义
printf("status=%d",WEXITSTATUS(status));
pid2=wait(&status);这个pid2是子进程的ID号
while(1){
printf("this is father getpid=%d\n",getpid());
sleep(3);
printf("%d\n",cnt);
}
}else if(pid==0){
while(1){
printf("this is child getpid=%d\n",getpid());
sleep(3);
cnt++;
if(cnt==3){
exit(-1);
}
}
}
waitpid
函数原型
#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid(pid_t pid,int *status,int options)
这样子进程也会变成僵尸进程
在父进程中等待子进程 因为父进程创建的就是子进程的pid号 所以等待的pid就是 子进程的
waitpid(pid,&status,WNOHANG);
孤儿进程
父进程在子进程的之前就结束了自己的生命 这种进程称为孤儿进程
子进程还在运行,init进程收留子进程,变成子进程的父进程
可以写为父进程就执行次,而子进程执行多次 父进程消失后,pid会变成init的进程号 1