僵尸进程:父进程不等待子进程退出,并且子进程先父进程退出,那么子进程变成僵尸进程
//运行以下代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
int status;
int i = 4;
pid_t pid = fork();
if(pid > 0)
{
while(1)
{
printf("this is father pid:%d\n",getpid());
sleep(3);
}
}
else if(pid == 0)
{
while(--i)
{
printf("this is child pid:%d\n",getpid());
sleep(3);
}
exit(2);
}
return ;
}
打开终端:这边打开了两个终端
如何查看僵尸进程:“z+”即僵尸进程
====================================================================================================================================================================================================================================
孤儿进程:父进程如果不等待子进程退出,在子进程之前就结束了自己的“生命”,此时子进程叫做孤儿进程
Linux为避免系统存在过多孤儿进程,init进程收留孤儿进程,变成孤儿进程的父进程
//运行以下代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
int status;
int i = 11;
pid_t pid = fork();
if(pid > 0)
{
printf("this is father pid:%d\n",getpid());
}
else if(pid == 0)
{
while(1)
{
printf("this is child pid:%d,father pid:%d\n",getpid(),getppid());
sleep(3);
}
exit(2);
}
return 0;
}
//结果如下:
this is father pid:6944
this is child pid:6945,father pid:6944
chm@ubuntu:~/linux$ this is child pid:6945,father pid:1722
this is child pid:6945,father pid:1722
this is child pid:6945,father pid:1722
...