一个守护进程的两种实现

简单实现

#include <unistd.h> #include <stdio.h> int do_sth() { //Add what u want return 0; } int main() { daemon(0,0); while ( 1 ) { do_sth(); sleep(1); } }

复杂实现:

实现守护进程的完整实例(每隔10s在/tmp/dameon.log中写入一句话):   =====================================================================   #include<stdio.h>   #include<stdlib.h>   #include<string.h>   #include<fcntl.h>   #include<sys/types.h>   #include<unistd.h>   #include<sys/wait.h>   #include <signal.h>   #define MAXFILE 65535   volatile sig_atomic_t _running = 1;   int main()   {   pid_t pc;   int i,fd,len;   char *buf="this is a Dameon/n";   len = strlen(buf);   pc = fork(); //第一步   if(pc<0){   printf("error fork/n");   exit(1);   }   else if(PC>0)   exit(0);   setsid(); //第二步   chdir("/"); //第三步   umask(0); //第四步   for(i=0;i<MAXFILE;i++) //第五步   close(i);   signal(SIGTERM, sigterm_handler);   while( _running ){   if((fd=open("/tmp/dameon.log",O_CREAT|O_WRONLY|O_APPEND,0600))<0){   perror("open");   exit(1);   }   write(fd,buf,len+1);   close(fd);   usleep(10*1000); //10毫秒   }   }   void sigterm_handler(int arg)   {   _running = 0;   }

经验分享 程序员 微信小程序 职场和发展