• 2.4 进程控制之僵尸进程和孤儿进程


    学习目标:理解僵尸进程和孤儿进程形成的原因

    一、孤儿进程

    1. 孤儿进程: 父进程先于子进程结束,则子进程成为孤儿进程。子进程成为孤儿进程之后,init进程则会成为其新的父进程,称为init进程领养孤儿进程。

    2. 例程:

     1 #include <stdio.h>
     2 #include <unistd.h>
     3 #include <sys/wait.h>
     4 
     5 int main(void)
     6 {
     7     pid_t pid;
     8     pid = fork();
     9 
    10     if (pid == 0) {
    11         while (1) {
    12             printf("I am child, my parent pid = %d
    ", getppid());
    13             sleep(1);
    14         }
    15     } else if (pid > 0) {
    16             printf("I am parent, my pid is = %d
    ", getpid());
    17             sleep(9);
    18             printf("------------parent going to die------------
    ");
    19     } else {
    20         perror("fork");
    21         return 1;
    22     }
    23     return 0;
    24 }

    编译与执行结果:

    二、僵尸进程

    1. 僵尸进程:一个进程使用fork创建子进程,如果子进程退出,而父进程并没有调用wait或waitpid获取子进程的状态信息,那么子进程的进程描述符仍然保存在系统中。这种进程称之为僵死进程。

    2. 例程:

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <unistd.h>
     4 #include <sys/wait.h>
     5 
     6 int main(void)
     7 {
     8     pid_t pid, wpid;
     9     pid = fork();
    10 
    11     if (pid == 0) {
    12             printf("---child, my parent= %d, going to sleep 10s
    ", getppid());
    13             sleep(10);
    14             printf("-------------child die--------------
    ");
    15     } else if (pid > 0) {
    16         while (1) {
    17             printf("I am parent, pid = %d, myson = %d
    ", getpid(), pid);
    18             sleep(1);
    19         }
    20     } else {
    21         perror("fork");
    22         return 1;
    23     }
    24 
    25     return 0;
    26 }

    编译与执行结果:

  • 相关阅读:
    mojoportal学习——文章翻译之SmartCombo
    windows froms 程序打包 (转载)
    [笔记]LCD1602 Display Experiment
    [笔记] JLink V8固件烧录指导
    [笔记]NiosII之Count Binary
    [笔记]DE2115 LCD1602字符的显示
    [笔记]What is HDBaseT
    [笔记]Inrush Current Case
    [笔记]远传中继的实现
    [笔记]RunningLED Experiment
  • 原文地址:https://www.cnblogs.com/lxl-lennie/p/10225322.html
Copyright © 2020-2023  润新知