什么是僵尸进程?
一个子进程在其父进程没有调用wait()或waitpid()的情况下退出。这个子进程就是僵尸进程。如果其父进程还存在而一直不调用wait,则该僵尸进程将无法回收,等到父进程结束后,会被init回收。
验证:
#include<stdio.h> #include<unistd.h> #include<stdlib.h> int main() { pid_t id=fork(); if(0 == id)//child { printf("child---pid:%d,ppid:%d\n",getpid(),getppid()); sleep(3); exit(1); } else //father { printf("father---pid:%d,ppid:%d\n",getpid(),getppid()); sleep(10); } return 0; }3秒后查询其进程信息:
通过上边两张图可以发现:
子进程24055的在三秒后的状态为Z(僵死状态),代表该进程为僵尸进程。
什么是孤儿进程?
一个父进程退出,而它的一个或多个子进程还在运行,那么这些子进程就是孤儿进程。孤儿进程将被init进程(1号进程)所收养,并由init进程对他们完成状态收集工作。
简单理解:我们现实中的孤儿,被福利中心收养。那么,此处的孤儿(孤儿进程),福利中心(init进程)。
验证:
#include<stdio.h> #include<unistd.h> #include<stdlib.h> int main() { pid_t id=fork(); if(0 == id)//child { while(1) { printf("child---pid:%d,ppid:%d\n",getpid(),getppid()); sleep(1); } } else //father { printf("father---pid:%d,ppid:%d\n",getpid(),getppid()); sleep(3); exit(1); } return 0; }
可以发现:刚开始(3秒内),子进程的父进程为24159。三秒后其父进程为1(init)