2013-12-15 41 views
5

我想知道如果下面的代碼可以創建殭屍:這個C代碼可以創建殭屍進程嗎?

#include <stdio.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h> 

int main(){ 
    int i=1; 
    pid_t p; 
    p = fork(); 
    i++; 
    if(p!=0){ 
     waitpid(p, NULL, 0); 
    } 
    printf("%d\n",i); 
    return 0; 
} 

所以,父進程調用子進程,如果孩子尚未退出後者立即返回waitpid函數。所以,迄今爲止沒有殭屍出現。但是,如果孩子在

return 0;
命令之前退出,那麼這將是一個殭屍呢?我實際上對此感到困惑。 waitpid是程序終止前的最後一行代碼嗎?任何幫助,將不勝感激。謝謝!

+1

看起來不錯,但您可能會有誤解。如果孩子已經死亡,'waitpid'會立即返回;否則會阻塞,直到孩子死亡。除非你在waitpid中使用WNOHANG,在這種情況下它不會阻塞,但這在這裏沒有問題。 – Duck

+0

糾正我,如果我錯了,但我認爲第三個參數(零)相當於WHOHANG。無論如何,我們假設它是WHOHANG。那麼殭屍會被創造出來嗎?最後,如果waitpid是返回0之前的最後一個命令;確保不會創造殭屍?再次感謝! – mgus

+1

沒有WNOHANG絕對不等於0.零是默認值,如果等於0,則按位或WNOHANG是沒有意義的。如果孩子在非阻塞的「waitpid」之後死亡並且父親先退出,那麼你會有殭屍。但通常你會在一個循環中使用一個非阻塞的'waitpid',並可能與接收SIGCHLD一起使用。 Waitpid本身可以在代碼中的任何地方,只要它在需要時處理你的孩子。 – Duck

回答

6

是否它結束孩子才能成爲殭屍的父母不叫wait*()只要本身住在。

在當下的父母也結束孩子都被init過程,會照顧到呼籲孩子wait*()收穫,所以它最終將結束,與此留下殭屍狀態,從進程列表中消失。

挑起您的示例代碼創建的孩子成爲一個殭屍修改代碼,舉例如下:

#include <stdio.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h> 

int main(void) 
{ 
    pid_t p = fork(); 

    if (p != 0) 
    { 
     waitpid(p, NULL, 0); /* See if the child already had ended. */ 
     sleep(1); /* Wait 1 seconds for the child to end. And eat away the SIGCHLD in case if arrived. */ 
     pause(); /* Suspend main task. */ 
    } 
    else 
    { 
     sleep(3); /* Just let the child live for some tme before becoming a zombie. */ 
    } 

    return 0; 
} 

由於以下兩個事實:

  • 孩子睡3秒所以父母打電話給waitpid()很可能總是會失敗
  • SIGCHLD的默認處理是忽略它。

以上事實的代碼是一樣的:

#include <stdio.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h> 

int main(void) 
{ 
    pid_t p = fork(); 

    if (p != 0) 
    { 
     pause(); /* Suspend main task. */ 
    } 
    else 
    { 
     sleep(3); /* Just let the child live for some tme before becoming a zombie. */ 
    } 

    return 0; 
} 
+0

這段代碼中有什麼可以防止孩子成爲殭屍?你能否更詳細地解釋你爲什麼使用睡眠和暫停命令?對不起,有很多問題,但我不熟悉這些概念。 – mgus

+0

@ Konstantinos Konstantinidis:「*這段代碼中有什麼能夠阻止孩子成爲殭屍?」沒有。正如我的回答所述,這段代碼**會創建一個殭屍。 – alk

0

我發現了一個簡單的方法來創建一個殭屍進程,用ps -e

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/wait.h> 

void main() 
{ 
    pid_t pid; 
    pid = fork(); 
    //parent sleeps while the child has exited 
    //not an orphan since parent still alive 
    //child will be still present in process table 
    if(pid==0) 
    {//child 
     exit(0); 
    } 
    else 
    {//parent 
     sleep(15); 
    } 
} 

運行ps的測試 - e在15秒內... 你會看到

6454 pts/2 00:00:00 a.out <不存在>