跟蹤子程序的死亡
如何追蹤子程序的死亡,而不會讓父程序等到子程序宕機之前呢?
我正在嘗試客戶端 – 伺服器場景,其中伺服器接受來自客戶端的連線,併為其接受的每個連線分配一個新程序.
我忽略了SIGCHLD訊號,以防止殭屍建立.
signal(SIGCHLD, SIG_IGN); while(1) { accept(); clients++; if(fork() ==0) { childfunction(); clients--; } else { } }
上述情況下的問題是,如果子程序在childfunction()函式中被殺死,則全域性變數客戶端不會遞減.
注意:我正在尋找解決方案,而不使用SIGCHLD訊號…如果可能的話
通常,您為SIGCHLD編寫一個處理程式,它在pid -1上呼叫waitpid().您可以使用該值的返回值來確定pid是否死亡.例如:
void my_sigchld_handler(int sig) { pid_t p; int status; while ((p=waitpid(-1, &status, WNOHANG)) != -1) { /* Handle the death of pid p */ } } /* It's better to use sigaction() over signal().You won't run into the * issue where BSD signal() acts one way and Linux or SysV acts another. */ struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = my_sigchld_handler; sigaction(SIGCHLD, &sa, NULL);
或者,您可以呼叫waitpid(pid,& status,0)指定子程序的ID,同步等待它宕機.或者使用WNOHANG來檢查其狀態而不會阻塞.
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/2377811/tracking-the-death-of-a-child-process