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

殭屍進程的避免
⒈父進程通過wait和waitpid等函數等待子進程結束,這會導致父進程掛起。
⒉ 如果父進程很忙,那麼可以用signal函數爲SIGCHLD安裝handler,因爲子進程結束後, 父進程會收到該信號,可以在handler中調用wait回收。
⒊ 如果父進程不關心子進程什麼時候結束,那麼可以用signal(SIGCHLD,SIG_IGN) 通知內核,自己對子進程的結束不感興趣,那麼子進程結束後,內核會回收, 並不再給父進程發送信號。
⒋ 還有一些技巧,就是fork兩次,父進程fork一個子進程,然後繼續工作,子進程fork一 個孫進程後退出,那麼孫進程被init接管,孫進程結束後,init會回收。不過子進程的回收 還要自己做。
#include "apue.h"
#include <sys/wait.h>
int main(void) ...{
pid_t pid;
if ((pid = fork()) < 0)
{
err_sys("fork error");
} else if (pid == 0) { /* first child */
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid > 0)
exit(0); /* parent from second fork == first child */
/ * We're the second child; our parent becomes init as soonas our real parent calls exit() in the statement above. Here's where we'd continue executing,knowing that whenwe're done,init will reap our status.*/
sleep⑵;
printf("second child,parent pid = %d ",getppid());
exit(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);
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章