您的位置:首页 > 运维架构 > Linux

Linux 僵尸进程 孤儿进程

2014-05-26 20:40 525 查看
今天有人问到了僵尸进程 和孤儿进程,以前遇到过,但是没有太注意,这里mark 一下

僵尸进程 :进程 fork 出来子进程,但是 父进程没有调用wait 或waitpid 获取子进程的状态信息,子进程的进程描述符任然保存在系统中

查找僵尸进程

ps -A -ostat,ppid,pid,cmd | grep -e '^[Zz]'

孤儿进程 :父进程退出,子进程任然在继续,孤儿进程将被init( 1) 收养,并由Init完成对他们的信息采集

僵尸进程的危害:进程退出时候,内核将释放所有资源,包括打开的文件、占用的内存的时候有,但是任然会保留一定的信息

,知道父进程通过wait/waitpid 来取的时候才释放,如果父进程不钓鱼wait waitpid ,这些保留的信息就不会释放,其进程号就会被一直占用,系统进程号有限,如果大量产生僵尸进程,系统就不能产生新的进程。

孤儿进程是没有父进程的进程,init 会负责善后工作,无什么危害

子进程(init除外) 在exit 后,不会马上消失,而是成为zombie,等待父进程处理

eg: 僵尸进程

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>

int main()
{
pid_t pid = fork();
if( pid < 0 )
{
printf("fork_error\n");
exit(1);
}
else if ( pid == 0 )
{
printf(" child \n");
exit(0);
}

printf("father....\n");
sleep(2);
system("ps -o pid,ppid,state,tty,command");
printf("father exit....");
return 0;
}


  其运行结果

  


  孤儿进程

  

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>

int main()
{
pid_t pid = fork();
if( pid < 0 )
{
printf("fork_error\n");
exit(1);
}
else if ( pid == 0 )
{
printf(" child \n");
printf("pid: %d\tppid:%d\n",getpid(),getppid());
printf("sleep ...");
sleep(4);
printf("pid: %d\tppid:%d\n",getpid(),getppid());
printf("child exit ...");
exit(0);
}

printf("father....\n");
printf("father exit....");
return 0;
}


  运行结果:

  

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: