linux进程退出 孤儿进程 僵尸进程

进程退出

#include <stdlib.h>
void exit(int status);

#include <unistd.h>
void _exit(int status);

复制代码
 1 /*
 2     #include <stdlib.h>
 3     void exit(int status);
 4 
 5     #include <unistd.h>
 6     void _exit(int status);
 7     
 8     status参数:进程退出时的一个状态信息,父进程回收子进程资源的时候可以获取到
 9 */
10 
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <stdio.h>
14 int main()
15 {
16     printf("hello\n");//printf是标准C库的函数
17     printf("world");//无\n  先将数据放到缓冲区 调用系统 _exit() 没有刷新缓冲区 没有显示world
18     //exit(0);//输出: hello\n world
19     //RETURN 0 与 EXIT(0) 都表示进程退出  EXIT(0)执行成功 return 0 就不会执行
20     _exit(0);//输出: hello  没有world   少用
21     return 0;
22 }
复制代码

孤儿进程   :默认父进程会等子进程运行结束,收回子进程的资源  

  父进程运行结束,但子进程还在运行(未运行结束),这样的子进程就称为 孤儿进程(Orphan Process)

  每当出现一个孤儿进程的时候,内核就把孤儿进程的父进程设置为 init, 而 init进程会循环地  wait()  它的已经退出的子进程。这样,当一个孤儿进程结束其生命周期的时候, init进程会处理善后工作。(init进程 pid为 1 系统进程)

  因此孤儿进程并不会有什么危害    

复制代码
 1 #include <sys/types.h>
 2 #include <unistd.h>
 3 #include <stdio.h>
 4 
 5 int main()
 6 {
 7     //创建子进程
 8     pid_t pid = fork();
 9     //判断是父进程还是子进程
10     if(pid > 0)//父进程
11     {
12         //如果大于0  返回的是 子进程的进程号
13         printf("parent process,pid:%d\t ppid:%d\n",getpid(),getppid());
14     }
15     else if(pid == 0)
16     {
17         sleep(1);//让父进程先结束
18         //子进程
19         printf("child process,pid:%d\t ppid:%d\n",getpid(),getppid());
20     }
21     //for 循环
22     for(int i = 0; i < 3; i++)
23     {
24         printf("i: %d\t pid:%d\n",i,getpid());
25     }
26     return 0;
27 }
复制代码

僵尸进程   

    每个进程结束之后,都会释放自己地址空间中的用户区数据,内核区的 PCB 没有办法自己释放掉,需要父进程去释放

  进程终止时,父进程尚未回收,子进程残留资源(PCB)存放于内核中,变成僵尸(Zombie)进程。

  僵尸进程不能被  kill  -9  杀死

  这样就会导致,如果父进程不调用  wait()  或者 waitpid() 的话,那么保留的那段信息就不会释放,其进程号就会一直被占用,但是系统所能使用的进程号是有限的,如果有大量的僵尸进程产生,将因为没有可用的进程号而导致系统不能产生新的进程,应当避免。        

复制代码
 1 #include <sys/types.h>
 2 #include <unistd.h>
 3 #include <stdio.h>
 4 
 5 int main()
 6 {
 7     //创建子进程
 8     pid_t pid = fork();
 9     //判断是父进程还是子进程
10     if(pid > 0)//父进程
11     {
12         while(1)
13         {
14             printf("parent process,pid:%d\t ppid:%d\n",getpid(),getppid());
15             sleep(1);//父进程循环 子进程结束 产生僵尸进程 Zombie
16             //杀死父进程 可以将僵尸进程赋给 pid = 1 解决僵尸进程 
17             //实际中程序运行可能无法杀死父进程 则需要使用 wait()函数
18         }   
19     }
20     else if(pid == 0)
21     {
22         printf("child process,pid:%d\t ppid:%d\n",getpid(),getppid());
23     }
24     //for 循环
25     for(int i = 0; i < 3; i++)
26     {
27         printf("i: %d\t pid:%d\n",i,getpid());
28     }
29     return 0;
30 }
复制代码

posted on   廿陆  阅读(20)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示