The Daemon (daemon) process, which is a background service process in Linux, usually takes a name ending in D, independently of the control terminal and periodically performing certain tasks or waiting to handle certain occurrences.
Characteristics:
No control terminal, can not directly and user interaction, not affected by user login, logoff, has been running
To create a daemon model:
1, create child process, parent process exits
2, create a new session in the child process, you can use the Setsid () function to make the child process completely independent
3, change the current directory to the root directory, you can use the ChDir () function, to prevent the consumption of the unmounted file system
4, reset file permission mask, umask () function to prevent inherited file creation from masking certain permissions
5, close the file descriptor, the inherited open will not be used
6, start to perform the daemon core work
7, Daemon quits processing
Specific implementation code:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include < unistd.h> #include <fcntl.h> #include <time.h> #include <sys/time.h> #include <signal.h># Include <sys/stat.h> #include <errno.h>int fd;//signal processing function void Sighandler (int signo) {//Get system time time_t tm;time ( &TM); char *p = CTime (&TM); write (FD, p, strlen (P));} int main () {pid_t Pid;int ret;//creates a child process, then the parent process exits PID = fork (), if (pid<0 | | pid>0) {exit (0);} Child process Creation New session setsid (); Change the current working directory Chdirchdir ("/home/pig/test");//Reset the file mask umask (0000);//Close the file descriptor of close (Stdin_fileno); close (Stdout_fileno); Close (Stderr_fileno);//Open a file FD = Open ("./test.log", O_RDWR | O_creat, 0777); if (fd<0) {perror ("open Error"); return-1;} Registered signal processing function struct Sigaction Act;act.sa_handler = Sighandler;act.sa_flags = 0;sigemptyset (&act.sa_mask); Sigaction ( SIGALRM, &act, NULL);//Call Setitimer function periodically send SIGALRM signal struct itimerval tm;tm.it_interval.tv_sec = 2;tm.it_interval.tv _usec = 0;tm.it_valUe.tv_sec = 3;tm.it_value.tv_usec = 0;setitimer (Itimer_real, &tm, NULL), while (1) {sleep (2);} Close (FD); return 0;}
Daemon model creation ideas and detailed implementation code