Linux殭屍進程(Zombie or defunct) 關於Linux殭屍進程,一般是由於子進程結束的時候,會有一些資源沒有釋放掉,直到父進程結束或者由父進程去處理它才可以! www.2cto.com 殭屍進程就是子進程已經結束,但是父進程沒有處理的進程! 父進程可以使用waitpid,wait等來處理殭屍進程! if 父進程不幸在子進程之前“死了”,那麼子進程就交由init( pid == 1 )進程去管理~ 我們可以測試以下: 具體的程式解釋看代碼的注釋! [cpp]#include <stdio.h> #include <stdlib.h> #include<sys/types.h> www.2cto.com int main() { int status; if(!fork()) //!> fork一個進程 { printf("child pid=%d\n", getpid()); exit(0); } printf("請輸入ps -e : 查看殭屍進程!\n"); sleep(10); //!> 讓你有時間去輸入ps -e查看 printf("下面讓父進程wait,來處理殭屍進程,請再ps -e查看! \n"); if( waitpid(-1, &status, 0) != -1 ) //!> 參數是-1就是等待所有的子進程 { printf( "子進程退出status:%d\n", status ); } else { printf("waitpid error!\n"); exit( 1 ); } sleep(10); //!> 讓你有時間去輸入ps -e查看 exit(0); } www.2cto.com gcc -o 1 1.c 我的機子上運行結果: 2747 pts/0 00:00:00 bash 2768 pts/0 00:00:00 1 //!> 看:這個就是父進程 2769 pts/0 00:00:00 1 <defunct> //!> 看:這個就是子進程成為殭屍進程 2772 pts/1 00:00:00 bash 2802 pts/1 00:00:00 ps pengtao@ubuntu:~$ //!> 10s 之後我開啟第二個終端ps -e 2747 pts/0 00:00:00 bash 2768 pts/0 00:00:00 1 //!> 沒有咯~~~呵呵~~~ 2772 pts/1 00:00:00 bash 2805 pts/2 00:00:00 bash 2821 pts/2 00:00:00 ps pengtao@ubuntu:~$ 當然我們可以使用忽略訊號,使得不產生殭屍進程! signal( SIGCHLD, SIG_IGN ); //!> 忽略產生殭屍進程 www.2cto.com [cpp]#include <stdio.h> #include <stdlib.h> #include<sys/types.h> #include <signal.h> int main() { int status; int i; signal( SIGCHLD, SIG_IGN ); //!> 忽略產生殭屍進程 for( i = 0; i < 5; i++ ) //!> 5個子進程 { if(!fork()) { printf("child pid=%d\n", getpid()); exit(0); } } printf("請輸入ps -e : 查看殭屍進程!\n"); www.2cto.com sleep(10); exit(0); } gcc -o 1 1.c 3115 pts/0 00:00:00 bash 3172 pts/1 00:00:00 bash 3228 pts/0 00:00:00 1 3237 pts/1 00:00:00 ps 所以一般情況下if需要子進程的結果來做一些判斷 ,那麼我們應該是需要wait或waitpid的,但是很多時候是可以直接忽略的,對於殭屍進程來說,消耗的src雖然少,但是一旦殭屍建成多了也是會影響效能的,所以還是需要注意的! 作者 shanshanpt