How do I implement the daemon process?

Source: Internet
Author: User
Tags syslog

A daemon (Daemon) is a special process that runs in the background. It is independent of the control terminal and periodically performs some sort of task or waits to handle certain occurrences. Daemons are a very useful process.

1. The most important feature of the daemon is running in the background.
2. The daemon must be isolated from the environment before it runs. These environments include file descriptors that are not closed, control terminals, session and process groups, working directories, and file creation masks. These environments are typically inherited by daemons from the parent process that executes it, especially the shell.
3, the daemon's starting mode has its special place. It can be started from the startup script/ETC/RC.D when the Linux system starts, can be started by the job planning process Crond, and can be executed by the user terminal (shell).

In short, despite these peculiarities, daemons are basically no different from ordinary processes. Therefore, the process of writing a daemon is actually transforming a normal process into a daemon based on the nature of the daemon described above. It is easier to understand and program if you have a more in-depth understanding of the process.

Programming rules for Daemon processes
(1) The first thing to do is to call Umask to set the file mode to create the mask word to 0.
File permission mask: refers to the corresponding bit in the file permission to block out. For example, there is a file permission mask of 050, which masks the readable and executable permissions of the filegroup owner (corresponding to binary, RWX, 101). Because the child process created by the Fork function inherits the file permission mask of the parent process, this creates a lot of trouble for the child process to use the file. Therefore, setting the file permission mask to 0 (that is, not masking any permissions) can enhance the daemon's flexibility. The function that sets the file permission mask is umask. The usual method of use is Umask (0).

(2) Call fork and then leave the parent process (exit).if(pid=fork()) exit(0);

(3) Call Setsid to create a new session, away from the control terminal and the process group . Setsid function: Used to create a new session and serve as the leader of the conversation group.

Calling Setsid has 3 functions: (a) freeing the process from the control of the original session, (b) freeing the process from the control of the original process group, and (c) freeing the process from control of the original control terminal;setsid()
Purpose of using the SETSID function: Because the first step of creating the daemon calls the fork function to create the child process and then exits the parent process. Because when the fork function is called, the child process copies the session period of the parent process, the process group, the control terminal, and so on, although the parent process exits, but the session period, the process group, the control terminal and so on have not changed, so this is not the true sense of independence opened. With the SETSID function, the process can be completely isolated from the control of other processes.

(4) Change the current working directory to the root directory.#define NOFILE 256 for(i=0;i<NOFILE;i++) close(i);

(5) Close file descriptors that are no longer needed. This causes the daemon to no longer hold some file descriptors inherited from its parent process (the parent process might be a shell process, or some other process).

(6) Some daemons open/dev/null to have file descriptors 0, 1, and 2, so any library routine that attempts to read standard input, write standard output, and standard error will have no effect. Because the daemon is not associated with an end device, it cannot display its output on the end device, and it has nowhere to accept input from the interactive user.

#include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/resource.h># include<unistd.h> #include <fcntl.h> #include <stdlib.h> #include <syslog.h> void Daemonize (      const char *cmd) {int I, fd0, FD1, FD2;      pid_t pid;      struct Rlimit RL;          struct Sigaction sa;   Umask (0);     Clear file Creation mask.         if (Getrlimit (Rlimit_nofile, &AMP;RL) < 0) {//Get maximum number of file descriptors.      Err_quit ("%s:can ' t get file limit", cmd);      } if (pid = fork ()) < 0) {//This step fork ensures that the process is not a process group leader process Err_quit ("%s:can ' t fork", CMD);      } else if (pid! = 0) {/* parent */exit (0);  } setsid ();      Create a reply, the session contains only the child process, and the child process is the first process of the session///session First process exit will depart SIGHUP signal default this signal operation will terminate the process */Sa.sa_handler = sig_ign;      Sigemptyset (&sa.sa_mask);      sa.sa_flags = 0; if (Sigaction (SIGHUP, &sa, NULL) < 0) {Err_quiT ("%s:can ' t ignore SIGHUP", cmd); }/* Create the child process again, exit the parent process, and ensure that the daemon is not the session first process, so that the open will not be assigned the terminal */if ((PID = fork ()) < 0) {err_quit ("%      S:can ' t fork, CMD);      } else if (pid! = 0) {/* parent */exit (0);      } if (ChDir ("/") < 0) {//change the current working path to the root directory err_quit ("%s:can ' t directory to/", CMD);      } if (Rl.rlim_max = = rlim_infinity) {//Close all open file descriptors Rl.rlim_max = 1024;      } for (i = 0; i < Rl.rlim_max; i++) {Close (i); }/* Because all of the file descriptors are closed, the open return must be a minimum of 0, and after two times the DUP returns 1, 2, which also completes the operation on standard input, standard output, and standard error redirection to/dev/null */FD      0 = open ("/dev/null", O_RDWR);      FD1 = DUP (0);      FD2 = DUP (0);      /* * Initialize the log file.      */Openlog (cmd, log_cons, Log_daemon); if (fd0! = 0 | | fd1! = 1 | | Fd2! = 2) {syslog (Log_err, "Unexpected file descriptors%d%d%d", fd0, FD1, FD          2);      Exit (1);   }  }

http://www.frankyang.cn/2017/05/25/daemon/

How do I implement the daemon process?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.