僵尸进程-Z(zombie)
子进程退出,父进程还在运行,但父进程没有读取子进程状态,子进程进入Z状态。
1 #include <iostream>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <sys/types.h>
5
6 using namespace std;
7
8 int main()
9 {
10 pid_t id = fork();
11 if(id == -1){
12 cerr << "fork error" << endl;
13 }
14 if(id == 0){
15 int count = 0;
16 while(1){
17 cout << "child is running..." << endl;
18 sleep(1);
19 if(count++ >= 5){
20 exit(1);
21 }
22 }
23 }
24 else{
25 while(1){
26 cout << "father is running..." << endl;
27 sleep(1);
28 }
29 }
30 return 0;
31 }
僵尸进程危害
- 进程的退出状态必须被维持下去,因为它要告诉关心它的进程(父进程),你交给我的任务,我办的怎么样了。可父进程如果一直不读取,那子进程就一直处于Z状态。
- 维护退出状态本身就是要用数据维护,也属于进程基本信息,所以保存在task_struct(PCB)中,Z状态一直不退出,PCB一直都要维护。
- 如果一个父进程创建了很多子进程,就是不回收,就会造成内存资源的浪费,数据结构对象本身就要占用内存。
- 造成内存泄漏。
孤儿进程
父进程先退出,子进程就称之为孤儿进程
1 #include <iostream>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <sys/types.h>
5
6 using namespace std;
7
8 int main()
9 {
10 pid_t id = fork();
11 if(id == -1){
12 cerr << "fork error" << endl;
13 }
14 if(id == 0){
15 while(1){
16 cout << "child is running..." << endl;
17 sleep(1);
18 }
19 }
20 else{
21 int count = 0;
22 while(1){
23 if(count++ >= 5){
24 exit(1);
25 }
26 cout << "father is running..." << endl;
27 sleep(1);
28 }
29 }
30 return 0;
31 }