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\n", getppid());
13             sleep(1);
14         }
15     } else if (pid > 0) {
16             printf("I am parent, my pid is = %d\n", getpid());
17             sleep(9);
18             printf("------------parent going to die------------\n");
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\n", getppid());
13             sleep(10);
14             printf("-------------child die--------------\n");
15     } else if (pid > 0) {
16         while (1) {
17             printf("I am parent, pid = %d, myson = %d\n", getpid(), pid);
18             sleep(1);
19         }
20     } else {
21         perror("fork");
22         return 1;
23     }
24 
25     return 0;
26 }

编译与执行结果:

猜你喜欢

转载自www.cnblogs.com/lxl-lennie/p/10225322.html