文章目錄
- 孤兒進程
- 概述
- 僵死進程
- 概述
孤兒進程
概述
父進程運行結束,子進程還在運行,此時,子進程就成了孤兒進程(Orphan Process)
每當出現一個孤兒進程的時候,內核就把孤兒進程的父進程設置為 init ,而 init 進程會循環地 wait() 它的已經退出的子進程。這樣,當一個孤兒進程凄涼地結束了其生命周期的時候,init 進程就會代表黨和政府出面處理它的一切善后工作。
因此孤兒進程并不會有什么危害。
1 #include <stdio.h>2 #include <string.h>3 #include <stdlib.h>4 5 #include <unistd.h>6 7 8 9 //孤兒進程10 11 int test01()12 {13 pid_t pid = -1;14 15 pid = fork();16 if(-1 == pid)17 {18 perror("fork"); 19 goto err0; 20 } 21 if(pid >0) 22 { 23 sleep(2); 24 printf("父進程退出 %d\n", getpid()); 25 exit(0); 26 } 27 28 while(1) 29 { 30 printf("子進程工作 %d...\n", getppid()); 31 sleep(1); 32 } 33 34 return 0; 35 err0: 36 return 1; 37 } 38 int main(void) 39 { 40 test01(); 41 return 0; 42 }
僵死進程
概述
進程終止,父進程尚未回收,子進程殘留資源(PCB)存放于內核中,變成僵尸(Zombie)進程。
這樣就會導致一個問題,如果進程不調用wait() 或 waitpid() 的話, 那么保留的那段信息就不會釋放,其進程號就會一直被占用,但是系統所能使用的進程號是有限的,如果大量的產生僵尸進程,將因為沒有可用的進程號而導致系統不能產生新的進程,此即為僵尸進程的危害,應當避免。
1 #include <stdio.h>2 #include <string.h>3 #include <stdlib.h>4 5 #include <unistd.h>6 7 8 9 int test01()10 {11 pid_t pid = -1;12 13 pid = fork();14 if(-1 == pid)15 {16 perror("fork");17 goto err0;18 }19 20 if(0 == pid)21 {22 printf("3s后子進程退出\n");23 sleep(3);24 printf("子進程退出...\n");25 exit(0);26 }27 else28 {29 30 sleep(3000);31 }32 33 34 return 0;35 err0:36 return 1;37 }38 39 int main()40 {41 test01();42 return 0;43 }