I. Daemon programming model
1 . Create a child process, the parent process exits all work in the subprocess formally out of control terminal 2. Create a new session in a child process the setsid () function makes the child process completely independent, out of control 3. Change the current directory to the root chdir () function to prevent the use of an unmounted file system can also be replaced by another path 4. reset File Permission Mask the Umask () function prevents inherited file creation masks from denying certain permissions (eventually inherited file screen words are inherited from the shell process, preventing inherited file creation masks from denying certain permissions) increasing daemon flexibility 5. Closing file Descriptor inherited open files will not be used, wasting system resources, unable to uninstall 6. Start the daemon core work 7. Daemon Exit Processing
Two. Code Model
Writes the current time in/tmp/damon.log every 10s
#include <stdio.h>#include<stdlib.h>#include<unistd.h>#include<sys/stat.h>#include<sys/types.h>#include<fcntl.h>#include<errno.h>#include<time.h>#include<string.h>#include<dirent.h>voiddaemonsize () {pid_t pid; if(PID = fork ()) <0) {perror ("Fork"); Exit (1); } Else if(PID! =0) {exit (3); } setsid (); Umask (0); if(ChDir ("/") <0) {perror ("chdir"); Exit (2); } Close (0); Open ("/dev/null", O_RDWR); Dup2 (0,1); Dup2 (0,2);}intMain () {daemonsize (); /*Write Current time To/tmp/dameon.log*/DIR*dir; if((Dir=opendir ("tmp")) ==NULL) { if(errno = =ENOENT) { if(MkDir ("./tmp",0777) <0) {perror ("mkdir"); Exit (4); } } Else{perror ("Opendir"); Exit (6); } } intFD; Umask (0); FD= Open ("./tmp/daemon.log", O_creat | O_RDWR,0777); if(FD <0) {perror ("Open"); Exit (5); } Charbuf[1024x768] = {0}; while(1) {time_t timep; if(Time (&TIMEP) <0) {perror (" Time"); Exit (6); } structTM *Now ; now= LocalTime (&TIMEP); memset (BUF,0,sizeof(BUF)); Strftime (BUF,sizeof(BUF),"%y-%m-%d%h:%m:%s \ n", now); Write (FD, buf, strlen (BUF)); Sleep (Ten); } return 0;}
Open/tmp/damon.log File
2018-03-29 14:54:29
2018-03-29 14:54:39
2018-03-29 14:54:49
2018-03-29 14:54:59
2018-03-29 14:55:09
2018-03-29 14:55:19
2018-03-29 14:55:29
2018-03-29 14:55:39
2018-03-29 14:55:49
2018-03-29 14:55:59
2018-03-29 14:56:09
2018-03-29 14:56:19
2018-03-29 14:56:29
2018-03-29 14:56:39
2018-03-29 14:56:49
2018-03-29 14:56:59
2018-03-29 14:57:09
2018-03-29 14:57:19
2018-03-29 14:57:29
2018-03-29 14:57:39
2018-03-29 14:57:49
2018-03-29 14:57:59
2018-03-29 14:58:09
2018-03-29 14:58:19
2018-03-29 14:58:29
2018-03-29 14:58:39
2018-03-29 14:58:49
2018-03-29 14:58:59
7. Daemon Process