1. 程式人生 > >編寫一unix程式,防止殭屍程序的出現.

編寫一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);
}