防止殭屍程序的fork程式設計

2021-07-14 16:27:14 字數 969 閱讀 8970

基本概念:

孤兒程序與殭屍程序

原理就是捕獲sigchld訊號,通過waitpid函式處理子程序退出,直接上**:

----- gcc fork_one.c -----

#include #include #include #include #include #include void sig_chld(int signo)

int main()

else

while (1)

}

ps:還有一種辦法就是雙重fork,讓子程序fork孫子程序,然後讓子程序退出,孫子程序歸init程序託管。

----- gcc fork_two.c -----

#include #include #include #include #include #include void perror(const char *s)

int main()

else if (pid == 0) else if (pid > 0)

sleep(2);

printf("second child pid = %ld, parent pid = %ld\n",

(long)getpid(), (long)getppid());

exit(0);

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

perror("waitpid error");

printf("parent for first child exit\n");

exit(0);

}

參考:《unix網路程式設計》·卷1、《unix環境高階程式設計》·第三版

兩次fork防止殭屍程序

1 何謂殭屍程序?在linux系統中,乙個已經終止但父程序尚未對其進行善後處理 釋放子程序相關資訊占用的資源 的子程序叫做殭屍程序 子程序結束時,父程序呼叫pid t wait int statloc 或者pid t waitpid pid t pid,int statloc,int options...

fork 與殭屍程序

使用fork 函式派生出多個子程序來並行執行程式的不同 塊,是一種常用的程式設計泛型。特別是在網路程式設計中,父程序初始化後派生出指定數量的子程序,共同監聽網路埠並處理請求,從而達到擴容的目的。但是,在使用fork 函式時若處理不當,很容易產生殭屍程序。根據unix系統的定義,殭屍程序是指子程序退出...

防止殭屍程序的產生

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