編寫一unix程式,防止殭屍程序的出現

2021-07-30 08:59:14 字數 735 閱讀 1964

殭屍程序的避免

⒈父程序通過wait和waitpid等函式等待子程序結束,這會導致父程序掛起。

⒉ 如果父程序很忙,那麼可以用signal函式為sigchld安裝handler,因為子程序結束後, 父程序會收到該訊號,可以在handler中呼叫wait**。

⒊ 如果

父程序不關心子程序什麼時候結束,那麼可以用signal(sigchld,sig_ign) 通知

核心,自己對子程序的結束不感興趣,那麼子程序結束後,核心會**, 並不再給父程序傳送訊號。

⒋ 還有一些技巧,就是fork兩次,父程序fork乙個子程序,然後繼續工作,子程序fork一 個孫程序後退出,那麼孫程序被init接管,孫程序結束後,init會**。不過子程序的** 還要自己做。

#include "apue.h"

#include int main(void) ... else if (pid == 0)

if (waitpid(pid,null,0) != pid) /* wait for first child */

err_sys("waitpid error");

/ * we're the parent (the original process); we continue executing,knowing that we're not the parent of the second child.*/

exit(0);

}

防止殭屍程序的產生

apue的 直接貼這裡。這段 採用了兩次fork,來避免產生殭屍程序。當乙個程序的父程序先退出,該程序就由init程序接管。init程序就成為了該程序的父程序 該程序退出時,有init來清理。所以該程序就不會成為殭屍程序了。include include include include intmai...

防止殭屍程序的方法

1.每次執行fork 前利用waitpid檢視是否有子程序需要處理 2.呼叫signal sigchld,fun 註冊訊號處理函式,在函式裡呼叫waitpid void fun int 3.利用 sigaction 結構體 struct sigaction act,oldset 設定訊號性質的結構體...

如何防止出現殭屍程序

include include int main else if pid 0 上述程式中,fork了乙個子程序,並且子程序很快就退出。父程序持續進行sleep,這樣子程序就變成了殭屍程序。利用ps命令可以清晰的看到這一點。leconte localhost ps axu greptest lecon...