守护进程(Daemon)是运行在后台的一种特殊进程,它独立与控制终端并且周期性的执行某种任务,是一个很有用的进程,linux大多数服务器就是用守护进程实现的,例如internet服务器inetd, web服务器httpd等;同时,守护进程完成许多系统任务;比如,作业规划进程crond,打印进程lpd
下面代码实现的是:
创建一个守护进程,该进程的作用是每个5秒往/var/bunfly.log文件中添加当前时间,格式规定为:2015-08-20 16:52:35
法一:利用 strftime()函数,具体用法用man手册
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <fcntl.h> 4 #include <time.h> 5 #include <string.h> 6 7 int main() 8 { 9 //step 1: parent exit 10 int pid = fork(); 11 if(pid > 0) { 12 exit(EXIT_SUCCESS); 13 } 14 15 //step 2: close tty 16 int ret = setsid(); 17 18 //step 3: close file descriptor 19 close(0); 20 close(1); 21 close(2); 22 23 //step 4: change directory 24 chdir("/"); 25 26 //step 5: set umask 27 umask(0); 28 29 //step 6: work 30 while(1) { 31 time_t now; 32 time(&now); 33 34 char s[32]; 35 strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S ", localtime(&now)); 36 37 int fd = open("/var/bunfly.log", O_RDWR | O_CREAT, 0664); 38 if(fd < 0) { 39 perror("open"); 40 exit(EXIT_SUCCESS); 41 } 42 43 lseek(fd, 0, SEEK_END); 44 write(fd, s, strlen(s)); 45 memset(s, 0, 32); 46 sleep(5); 47 } 48 }
法二:利用spriintf()函数
1 #include <stdio.h> 2 #include <fcntl.h> 3 #include <string.h> 4 #include <stdlib.h> 5 #include <time.h> 6 7 int main() 8 { 9 pid_t pid = 0; 10 //step 1: exit parent 11 pid = fork(); 12 if(pid < 0) { 13 perror("fork"); 14 exit(EXIT_FAILURE); 15 } 16 17 if(pid > 0) { 18 exit(EXIT_SUCCESS); 19 } 20 21 //step 2: exit tty 22 setsid(); 23 24 //step 3: close file descriptor 25 close(0); 26 close(1); 27 close(2); 28 29 //step 4: chage directory 30 chdir("/"); 31 32 //step 5: set umask 33 umask(0); 34 35 //step 6: working 36 while(1) { 37 time_t now; 38 time(&now); 39 char nowtime[100] = {0}; 40 struct tm *p = gmtime(&now); 41 42 sprintf(nowtime, "%d-%0.2d-%0.2d %0.2d:%0.2d:%0.2d ",p->tm_year + 1900, p->tm_mon + 1, p->tm_mday, p->tm_hour + 8, p->tm_min, p->tm_sec); 43 44 int fd = open("/var/dream", O_RDWR|O_CREAT, 0644); 45 if(fd < 0) { 46 perror("open"); 47 exit(EXIT_FAILURE); 48 } 49 50 lseek(fd, 0, SEEK_END); 51 write(fd, nowtime, strlen(nowtime)); 52 memset(nowtime, 0, 100); 53 sleep(5); 54 } 55 56 return 0; 57 } 58