Concept
The Daemon (daemon) process, a background service process in Linux, is a long-lived process, usually independent of the control end
and periodically perform some sort of task or wait to handle certain occurrences.
Model
Daemon Process Programming Steps
1. Create child process, parent process exits
All work is done in child processes
Formally out of control terminal
2. Create a new session in a child process
Setsid () function
Make a child process completely independent, out of control
3. Change the current directory to the root directory
ChDir () function
Prevents the use of an unmounted file system
can also be replaced by other paths
4. Resetting the file permission mask
Umask () function
Prevent inherited file creation masks from denying certain permissions
Increased daemon Flexibility
5. Close the file descriptor
Inherited open files are not used, waste system resources, cannot be uninstalled
6. Start the daemon core work
7. Daemon Exit Process
Code Model
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
void Daemonize (void)
{
pid_t pid;
/*
* Become a new session of the first process, lose control terminal
*/
if (PID = fork ()) < 0) {
Perror ("fork");
Exit (1);
} else if (pid! = 0)/*/parent */
Exit (0);
Setsid ();
/*
* Change the current working directory to/directory.
*/
if (ChDir ("/") < 0) {
Perror ("ChDir");
Exit (1);
}
/* Set Umask to 0 */
Umask (0);
/*
* Redirect 0,1,2 file descriptor to/dev/null, because the control terminal has been lost, then operation 0,1,2 No meaning.
*/
Close (0);
Open ("/dev/null", O_RDWR);
Dup2 (0, 1);
Dup2 (0, 2);
}
int main (void)
{
Daemonize ();
while (1); /* The core work of the daemon can be implemented in this cycle */
}
Running this program, it becomes a daemon and is no longer associated with the current terminal. Cannot be seen with the PS command, must be shipped
You can see the PS command with the x parameter. You can also see that the user closes the terminal window or logs off without affecting the daemon
The run of the process.
Daemons in Linux