linux服務端程序都需要提供7 * 24不間斷的服務,如何保證工作進程一直不退出或者不被kill掉,常見的方法就是啓動一個守護進程來檢測工作進程的狀態,如果發現工作進程退出,就再fork一個出來。一般的實現見下面一段代碼:
- // 守護進程(父進程)
- int status;
- for ( ; ; ) {
- if ( 0 == ( pid = fork()) ) {
- // 工作進程(子進程)
- run();
- }
- waitpid(-1, &status, 0);
- if (WIFEXITED(status))
- if (WEXITSTATUS(status) == 0)
- exit(0);
- if (WIFSIGNALED(status)) {
- switch (WTERMSIG(status)) {
- case SIGKILL:
- exit(0);
- break;
- case SIGINT:
- case SIGTERM:
- exit(1);
- default:
- break;
- }
- }
- }
- struct wait{
- # if __BYTE_ORDER == __LITTLE_ENDIAN
- unsigned int __w_termsig:7; /* Terminating signal. */
- unsigned int __w_coredump:1; /* Set if dumped core. */
- unsigned int __w_retcode:8; /* Return code if exited normally. */
- unsigned int:16;
- # endif /* Little endian. */
- };
- WIFEXITED(status) //子進程調用exit()或者從main return退出時爲true;
- WEXITSTATUS(status) //在WIFEXITED爲true時,表示exit()或return的返回碼;
- WIFSIGNALED(status) //子進程被信號終止時爲true;
- WTERMSIG(status) //在WIFSIGNALED爲true時,表示終止子進程信號的值;
- /* If WIFEXITED(STATUS), the low-order 8 bits of the status. */
- #define __WEXITSTATUS(status) (((status) & 0xff00) >> 8)
- /* If WIFSIGNALED(STATUS), the terminating signal. */
- #define __WTERMSIG(status) ((status) & 0x7f)
- /* Nonzero if STATUS indicates normal termination. */
- #define __WIFEXITED(status) (__WTERMSIG(status) == 0)
- /* Nonzero if STATUS indicates termination by a signal. */
- #define __WIFSIGNALED(status) \
- (((signed char) (((status) & 0x7f) + 1) >> 1) > 0)
- // 守護進程(父進程)
- int status;
- for ( ; ; ) {
- if ( 0 == ( pid = fork()) ) {
- // 工作進程(子進程)
- run();
- //信號處理函數signal_handler
- if (sig == SIGTERM || sig == SIGINT) {
- destroy();
- return 0;
- }
- }
- waitpid(-1, &status, 0);
- if (WIFEXITED(status) && (WEXITSTATUS(status) == 0)) exit(0);
- }
- The only signals that can be sent task number one, the init process, are those for which init has explicitly installed signal handlers. This is done to assure the system is not brought down accidentally.
- SV1:23:respawn:/usr/local/bin/svscanboot
原文地址:http://nil-zhang.iteye.com/blog/1806356