Implementation of Daemon daemon under Linux (for example, Nginx code)

Source: Internet
Author: User
Tags sigint signal

Ngx_int_tngx_daemon (ngx_log_t*log) {    intFD; //make the INIT process the parent process of the newly generated process://after calling the fork function to create the child process, the parent process exits immediately. In this way, the resulting subprocess becomes an orphan process and is taken over by the Init process,//at the same time, the resulting new process will become run in the background.     Switch(fork ()) { Case-1: Ngx_log_error (Ngx_log_emerg, log, Ngx_errno,"Fork () failed"); returnNgx_error;  Case 0:         Break; default: Exit (0); } ngx_pid=Ngx_getpid (); //Call the Setsid () function off the control terminal and the process group so that the process becomes the session leader and detached from the original logon session and process group. //at this point the process has become a non-terminal session leader, but it can re-apply to open a control terminal. //to avoid this situation, you can prevent the process from reopening the control terminal by making the process no longer a session leader.//This requires a second call to the fork () function (Nginx did not do this step). The parent process (session leader) exits and the child process resumes execution,//and no longer has the ability to open control terminals. After calling Init_daemon in the process being executed, the process becomes the daemon,//The out-of-control terminal executes in the background.     if(Setsid () = =-1) {ngx_log_error (Ngx_log_emerg, log, Ngx_errno,"Setsid () failed"); returnNgx_error; }     //Resetting document creation masks//in many cases, the daemon creates some temporary files.    For security reasons, it is often not desirable for these files to be viewed by other users. //At this point, you can use the Umask function to modify the file permissions and create a mask value to meet the requirements of the daemon. Umask0); //Close the Open document descriptor://The newly generated process inherits some open file descriptors from the parent process, and if you do not use these file descriptors, you need to close them. //daemons are running in the background of the system and should not have any output information at the terminal. //You can use the DUP function to redirect standard input, output, and error output to a/dev/null device//(/dev/null is an empty device that writes data to it without any output). FD = open ("/dev/null", O_RDWR); if(FD = =-1) {ngx_log_error (Ngx_log_emerg, log, Ngx_errno,"open (\ "/dev/null\") failed"); returnNgx_error; }     if(Dup2 (fd, stdin_fileno) = =-1) {ngx_log_error (Ngx_log_emerg, log, Ngx_errno,"dup2 (STDIN) failed"); returnNgx_error; }     if(Dup2 (fd, stdout_fileno) = =-1) {ngx_log_error (Ngx_log_emerg, log, Ngx_errno,"dup2 (STDOUT) failed"); returnNgx_error; } #if0if(Dup2 (fd, stderr_fileno) = =-1) {ngx_log_error (Ngx_log_emerg, log, Ngx_errno,"dup2 (STDERR) failed"); returnNgx_error; }#endif     if(FD >Stderr_fileno) {        if(Close (FD) = =-1) {ngx_log_error (Ngx_log_emerg, log, Ngx_errno,"Close () failed"); returnNgx_error; }    }     //change the current working directory (Nginx did not do)//The child processes that are produced by using the fork function inherit the current working directory of the parent process. //when a process does not end, its working directory cannot be unloaded. //to prevent this from happening, the daemon typically changes its working directory to the root directory (/directory).      returnNgx_ok;}

Setsid Related knowledge:

By calling the Setsid function, the newly created process leaves the control terminal, creates a new process group, and becomes the first process of the process group. To give the reader a better understanding of this step, the following is the basic concept of a process group, session.

In a Linux system, all processes belong to their own group of processes. A process group is a collection of one or more processes. For example, you can think of a class as a process group, where members are processes. A class has at least one member. When the last member of a class does not exist, the class does not exist, that is, the process group dies.

Each process group has an identity that is similar to the process number, called the process group ID. The process group ID is determined by the process number of the lead process, and there is a lead process for each process group. The presence or absence of a process group is not related to the presence of the lead process.

A session is a collection of one or more process groups. Like a process group, there is a lead process for each session. Linux is a multi-user operating system in which multiple processes belonging to different users exist in the system at the same time. If a user sends a signal on a terminal, for example, by pressing "CTRL + C" to send a SIGINT signal, how to ensure that the signal is correctly sent to the corresponding process without affecting the process of the user using the other terminal?

Sessions and process groups are the methods that the Linux kernel uses to manage user processes in multi-user situations. Each process belongs to a process group, and the process group belongs to a session. When a user logs on to the system from the terminal (whether it is a terminal or a pseudo-terminal), a new session is created. Processes that are started on the terminal will be placed in the process group of the session by the system.

A process in a session is connected to a terminal through the lead process in the session (often referred to as the control process). The terminal is the control terminal of the session. A session can have only one control terminal, and vice versa. If a session has a control terminal, it must have a foreground process group. Processes that belong to this group can get input from the control terminal. At this point, the other process groups are background process groups. Figure 8.3 shows the relationship between the session, the process group, the process, and the control terminal.

Because the daemon does not control the terminal, and the child process created with the Fork function inherits the control terminal, session, and process group of the parent process, a new session must be created to disengage from the parent process. The Linux system provides the SETSID function to create a new session.

The SETSID function creates a new session and causes the process that invokes the SETSID function to be the lead process for a fresh session. The process that calls the SETSID function is the only process group in the newly created session, and the process group ID is the process number of the calling process. The SETSID function produces this result with a condition that the calling process is not the lead process for a process. Because the parent process that called fork in the first step exits, the child process cannot be the lead process for the process group. The lead process for this session has no control over the terminal to be connected. At this point, the daemon does not have to control the terminal requirements.

Reference: http://www.cnblogs.com/xuxm2007/archive/2011/07/29/2121280.html

Implementation of Daemon daemon under Linux (for example, Nginx code)

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.