一个Linux守候进程例子


其他程序可以调用void daemon_init(const char * cmd)方法,来初始化当前进程为守候进程

  1. #include<stdio.h>   
  2. #include<unistd.h>   
  3. #include<sys/resource.h>   
  4. #include<fcntl.h>   
  5. #include<signal.h>   
  6. #include<syslog.h>   
  7. void daemon_init(const char * cmd);   
  8. int main(int argc, char * argv[])   
  9. {   
  10.     daemon_init("liyachao_d");   
  11.     time_t ticks;   
  12.     while(1)   
  13.     {   
  14.         sleep(60);   
  15.         ticks = time(NULL);   
  16.         syslog(LOG_INFO,"%s",asctime(localtime(&ticks)));   
  17.     }   
  18.     return 0;   
  19. }   
  20. void daemon_init(const char * cmd)   
  21. {   
  22.     int i;   
  23.     int fd0;   
  24.     int fd1;   
  25.     int fd2;   
  26.     pid_t pid;   
  27.     struct rlimit rl;   
  28.     struct sigaction sa;   
  29.     /*清空文件默认生成权限*/  
  30.     umask(0);   
  31.     /*取得最大的文件描述符*/  
  32.     if(getrlimit(RLIMIT_NOFILE,&rl) < 0 )   
  33.     {   
  34.         printf("can't get file limit.");   
  35.     }   
  36.     pid = fork();   
  37.     if(pid < 0 )   
  38.     {   
  39.         printf("fork error.");   
  40.         exit(1);   
  41.     }   
  42.     else if(pid > 0)   
  43.     {   
  44.         exit(0);   
  45.     }   
  46.     setsid();   
  47.     /*  
  48.     Ensure future opens won't allocate controlling TTYs.  
  49.  
  50.     */  
  51.     sa.sa_handler =SIG_IGN;   
  52.     sigemptyset(&sa.sa_mask);   
  53.     sa.sa_flags = 0;   
  54.     if(sigaction(SIGHUP,&sa,NULL) < 0 )   
  55.     {   
  56.         printf("catn't ignore SIGHUP");   
  57.         exit(1);   
  58.     }   
  59.        
  60.     pid = fork();   
  61.     if(pid < 0 )   
  62.     {   
  63.         printf("child fork error.");   
  64.         exit(1);   
  65.     }   
  66.     else if(pid > 0)   
  67.     {   
  68.         exit(0);   
  69.     }   
  70.     /*改变工作目录到root*/  
  71.     if(chdir("/") < 0 )   
  72.     {   
  73.         printf("can't change directory to /");   
  74.         exit(1);   
  75.     }   
  76.     /*关闭所有的文件描述符*/  
  77.     if (rl.rlim_max == RLIM_INFINITY)   
  78.     {   
  79.         rl.rlim_max = 1024;   
  80.     }   
  81.     for (i = 0; i < rl.rlim_max; i++)   
  82.     {   
  83.         close(i);   
  84.     }   
  85.     /*重定向文件描述符0,1,2,到/dev/null*/  
  86.     fd0 = open("/dev/null",O_RDWR);   
  87.     fd1 = open("/dev/null",O_RDONLY);   
  88.     fd2 = open("/dev/null",O_RDWR);   
  89.     openlog(cmd, LOG_CONS, LOG_DAEMON);   
  90.     /*初始化日志文件*/  
  91.     if (fd0 != 0 || fd1 != 1 || fd2 != 2)    
  92.     {   
  93.         syslog(LOG_ERR, "unexpected file descriptors %d %d %d",fd0, fd1, fd2);   
  94.         exit(1);   
  95.   
  96.     }   
  97. }  

相关内容