版权声明:本文为作者创作,转载请注明出处:http://blog.csdn.net/claroja,如有商业用途请联系QQ:63183535。 https://blog.csdn.net/claroja/article/details/89094062
孤儿进程:父进程死,子进程被init领养
子进程被领养后,ctrl+c不能停止,因为该bash已经没有子进程了,只能通过kill杀死
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
pid = fork();
if (pid == 0) {
while (1) {
printf("子进程,我的父 = %d\n", getppid());
sleep(1);
}
} else if (pid > 0) {
printf("父进程,我的子 = %d\n", getpid());
sleep(9);
printf("------------parent going to die------------\n");
} else {
perror("fork");
return 1;
}
return 0;
}
僵尸进程:子进程死了,父进程没有回收子进程的资源(PCB)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid, wpid;
pid = fork();
if (pid == 0) {
printf("子进程,我的父= %d, going to sleep 10s\n", getppid());
sleep(10);
printf("-------------child die--------------\n");
} else if (pid > 0) {
while (1) {
printf("父进程, pid = %d, 我的子 = %d\n", getpid(), pid);
sleep(1);
}
} else {
perror("fork");
return 1;
}
return 0;
}
僵尸进程不能用kill命令清掉,因为僵尸进程已经终止了.可以通过杀死父进程,来杀死僵尸进程.
当进程终止时,操作系统会:
1.关闭所有文件描述符
2.释放分配的内存空间
但是内核的PCB仍存在,其中保存着(正常终止→退出值;异常终止→终止信号)
父进程调用wait函数可以回收子进程终止信息。该函数有三个功能:
① 阻塞等待子进程退出
② 回收子进程残留资源
③ 获取子进程结束状态(退出原因)。
pid_t wait(int *status); 成功:清理掉的子进程ID;失败:-1 (没有子进程)
pid_t waitpid(pid_t pid, int *status, in options); 成功:返回清理掉的子进程ID;失败:-1(无子进程)