父进程处于不可中断睡眠状态,子进程可中断睡眠状态
#僵尸进程
僵子进程退出时会告诉父进程子进程任务完成怎么样了,如果父进程不关心子进程的退出,那么子进程就会变成僵尸进程,父进程不读取,子进程就一直为僵尸进程,造成内存泄漏。
下面通过代码演示僵尸进程
父进程睡眠30秒,子进程在创建后5秒退出,此时父进程在睡眠,无法获取子进程状态,子进程变为僵尸进程
#include#include#includeintmain(){
pid_t pid =fork();if(pid <0){printf("Create child process error!
");}elseif(pid >0){printf("This is parent process, pid->%d, begin to sleep!
",getpid());sleep(30);}else{printf("Child process's pid->%d, begin Z...
",getpid());sleep(5);exit(EXIT_SUCCESS);}return0;}
一开始的5秒内两个进程均正常,5秒后子进程退出,父进程没有读取到信息变成了僵尸进程
##如何避免僵尸进程
让父进程来回收子进程,调用wait()或waitpid()函数来关注子进程的状态,通知内父进程回收(wait()的用法之后会另外写一篇博客)
或者让子进程变成孤儿进程由init回收
#孤儿进程
父进程先于子进程退出,那么子进程就成为了孤儿进程,这个孤儿进程将被孤儿院init进程所领养,子进程退出后将由init进程来回收释放资源
孤儿进程举例:
#include#include#includeintmain(){int val =100;
pid_t pid =fork();if(pid <0){printf("Create process failed!!
");return-1;}elseif(pid >0){printf("This is parent process, it's pid is %d, prepare to exit in 15 seconds!
",getpid());sleep(15);printf("Parent process exit now!
");exit(0);}printf("This id child process, it's pid is %d
",getpid());while(1){sleep(1);}return0;}
代码演示结果