Nginx Learning 13 Initial fork and Nginx Daemon Ngx_daemon

Source: Internet
Author: User
Tags session id

Learning Nginx has been one months, and feel more and more difficult, the main reasons for their own summary: 1 platform is based on Linux, has hardly ever contacted Linux, and Nginx used a lot of Linux functions, 2 is the process, this thing contact is very little, Linux multi-process, not to mention, and now just see here, feel unusually strenuous, this does not see the establishment of Nginx daemon process, look for information to study well, so this article has learned fork as the main content.

OK, let's look at the setup of the Nginx daemon, and then learn to fork.

http://blog.csdn.net/xiaoliangsky/article/details/39998373

1nginx Daemon

Look directly at the code:

ngx_int_t Ngx_daemon (ngx_log_t *log) {int fd; Switch (fork ()) {//fork Create Daemon case-1://fork return-1 Create failed Ngx_log_error (Ngx_log_emerg, log, Ngx_errno, "fork () faile        D ");    return ngx_error;    Case 0://child process returns break;    DEFAULT://Parent Process returns exit (0);//parent process exits} Ngx_pid = Ngx_getpid ();        if (setsid () = =-1) {//Establish a new session, then the subprocess is called the session leader Ngx_log_error (Ngx_log_emerg, log, Ngx_errno, "Setsid () failed");    return ngx_error;    } umask (0);//Reset file creation Mask/* REDIRECT standard input, output to/dev/null (legendary black hole) */fd = open ("/dev/null", O_RDWR);        if (fd = =-1) {Ngx_log_error (Ngx_log_emerg, log, Ngx_errno, "open (\"/dev/null\ ") failed");    return ngx_error; } if (Dup2 (fd, stdin_fileno) = =-1) {//input redirected to FD, i.e. input ngx_log_error from/dev/null (Ngx_log_emerg, log, Ngx_errno, "dup2        (STDIN) failed ");    return ngx_error; } if (Dup2 (fd, stdout_fileno) = =-1) {//output redirected to FD, i.e. all output to/dev/null ngx_log_error (Ngx_log_emerg, log, Ngx_errno, "D Up2 (STDOut) failed ");    return ngx_error;         } #if 0 if (dup2 (fd, stderr_fileno) = =-1) {Ngx_log_error (Ngx_log_emerg, log, Ngx_errno, "Dup2 (STDERR) failed");    return ngx_error; } #endif if (fd > Stderr_fileno) {if (Close (FD) = =-1) {Ngx_log_error (Ngx_log_emerg, log, Ngx_err            No, "close () failed");        return ngx_error; }} return NGX_OK;}
Not much to explain here, read the following content, you know the above code is very simple.

2fork function

A new process created by Fork is called a subprocess (child process). The function is called once, but returns two times. The difference of two returns is that the return value of the child process is 0, and the return value of the parent process is the process ID of the new process (child process). The reason for returning the child process ID to the parent process is that because there can be more than one child process for a process, there is no function that enables a process to obtain the process ID of all its child processes. For a child process, fork returns 0 to it because it can call Getpid () to get its own PID at any time, or call Getppid () to get the ID of the parent process. (Process ID 0 is always used by the interchange process, so the process ID of a child process cannot be 0).

After fork, the operating system replicates a child process that is exactly the same as the parent process, although it is a parent-child relationship, but in the operating system it appears that they are more like siblings, that the 2 processes share the code space, but that the data space is independent and that the content in the child process data space is a complete copy of the parent process. The instruction pointer is also exactly the same, the child process has the parent process currently running to the location (the two process of the program counter PC value is the same, that is, the child process starts from the fork to execute), but a little different, if the fork is successful, the return value of fork in the sub-process is 0, The return value of the fork in the parent process is the process number of the child process, and if the fork is unsuccessful, the parent process returns an error.

Here's a few words:

int main () {int   count;int   flag;    pid_t pid;    PID = fork ();    if (PID > 0)    {        printf ("Parent process is run\n"); flag = 1;    }    else if (PID < 0)    {        printf ("Fork is error\n");        Exit ( -1);    }    else    {        printf ("Child is run \ n"); flag = 0;    }    Count = 0;if (flag) {printf ("Count in parent is:%d\n", ++count);} else{printf ("Count in:%d\n", ++count);} return 0;}
The results of the operation are as follows:

Parent process is runcount in parent Is:1child are run count in child is:1
From this example, you can know:

1 The parent and child processes execute the same code

2 The parent and child processes do not share data spaces, otherwise the value of count cannot be the same.

The 3fork process returned two times, and the parent process returned with a PID greater than 0, pid=0 when the child process returned, and the child process began executing at the return.


The following is the relationship between parent-child processes detailed in advanced programming.

Fork out of the sub-process, basically except the process number of the parent process of all things have a copy, basically means not all, the next thing we want to say is the child process from the parent process inherited something, what is not inherited. It is also important to note that the child process gets only a copy of the parent process, not the parent process resource itself.

Child processes inherit from the parent process to:
1. Eligibility for the process (real/active (Effective)/saved (saved) user number (UIDs) and group number (Gids))
2. Environment (Environment)
3. Stacks
4. Memory
5. Open the file descriptor (note that the location of the corresponding file is shared by the parent-child process, which can cause ambiguity)
6. Close on Execution (CLOSE-ON-EXEC) flag (Translator Note: The CLOSE-ON-EXEC flag can be set by Fnctl () to the file descriptor, POSIX.1 requires that all directory streams must be closed when the EXEC function is called. In more detail, see Advanced Programming for UNIX Environment W. R. Stevens, 1993, Yu Jinyuan, etc. (hereinafter referred to as "advanced Programming"), 3.13 knots and 8.9 sections)
7. Signal (signal) control settings
8.nice Value (Translator Note: Nice value is set by the Nice function, which represents the priority of the process, the smaller the value, the higher the priority)
Process scheduling category (Scheduler Class) (Translator Note: The process scheduling category refers to the class that the process belongs to when it is dispatched in the system, different classes have different priorities, and the process Scheduler calculates the global priority of each process based on the process scheduling category and the nice value. Prority), priority-high process priority execution)
8. Process group number
9. Session ID (Translator NOTE: Translated from advanced programming, refers to the session ID of the session to which the process belongs, a conversation period consists of one or more process groups, see Advanced Programming Section 9.5 for more detailed instructions)
10. Current working Directory
11. Root directory (Translator note: The root directory is not necessarily "/", it can be changed by the chroot function)
12. File mode to create a shielded word (File mode creation mask (umask)) (Translator Note: The translation is from Advanced programming, which refers to: Create a new file default screen word)
13. Resource Limitations
14. Control Terminal

The child process is unique:
Process number
1. Different parent process number (Translator Note: The parent process number of the child process is different from the parent process number, the parent process number can be obtained by the GETPPID function)
2. Copy of your own file descriptor and directory stream (translator Note: The directory stream is created by the Opendir function, because it is read sequentially, and is called "Directory Flow")
3. The child process does not inherit the process of the parent process, body (text), data and other locked memory (locks) (Translator Note: Locked memory refers to locked virtual memory pages, locked, 4. The kernel is not allowed to swap out when necessary (page out), see the GNU C Library Reference Manual Edition 2.2, 1999, 3.4.2)
5. System time in the TMS structure (translator Note: The TMS structure can be obtained by the Times function, which holds four data to record the time that the process uses the central processing Unit (cpu:central processing units), including: User Time, System time, total user time for each child process , total time for each sub-process of the system)
6. Resource Usage (resource utilizations) set to 0
8. Block signal sets are initialized to an empty set (translator Note: The original text is ambiguous here, the translation is slightly modified according to the Fork Function manual page)
9. Do not inherit timers created by the Timer_create function
10. Do not inherit asynchronous inputs and outputs

3 Creation of daemon processes

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. Second, 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. Finally, the way the daemon is launched 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 performed by the user terminal (usually the shell).

Steps to create the daemon:

1) running in the background

To avoid suspending the control terminal, put the daemon into the background. The method is to call fork in the process to terminate the parent process, allowing Daemon to execute in the background in the child process:

   PID = fork ();    if (PID > 0)    {        printf ("Parent is exit\n");        Exit (0);//parent process exits    }
2) out of control terminal, login session and process group

The relationship between a process in Linux and a control terminal, a logon session, and a process group: a process belongs to a process group, and a process group number (GID) is the process leader of the process (PID). A logon session can contain multiple process groups. These process groups share a control terminal. This control terminal is usually the login terminal of the creation process. Control terminals, logon sessions and process groups are usually inherited from the parent process. Our aim is to get rid of them so that they are not affected by them. The method is based on the 1th, call Setsid () to make the process a conversation leader:

if (setsid () = =-1) {printf ("Setsid is failed\n");}
After the Setsid () call succeeds, the process becomes the new session leader and the new process leader, and is detached from the original logon session and process group. Due to the exclusivity of the session process to the control terminal, the process is disconnected from the control terminal at the same time.

3) Disable the process to reopen the control terminal (this step is optional, see the situation)
Now, the process has become a session leader without terminal. But it can be re-applied to open a control terminal. You can prevent a process from reopening the control terminal by making the process no longer a session leader:

if (Pid=fork ()) exit (0); End first child process, second child process continues (second child process is no longer a conversation leader)
4) If you have an open file, close the Open file descriptor

The process inherits the open file descriptor from the parent process that created it. Without shutting down, system resources will be wasted, causing the file system where the process is located to fail to unload and cause unexpected errors.

For (I=0;i<=getdtablesize (); i++) Close (i)

5) Change the current working directory (see situation)
The file system in which the working directory resides cannot be unloaded while the process is active. It is generally necessary to change the working directory to the root directory. For processes that need to dump cores, the process that writes the log runs changes the working directory to a specific directory.

ChDir ("/tmp")

6) Reset File creation mask
The process inherits the file creation mask from the parent process that created it. It may modify the access bit of the file created by the daemon. To prevent this, the file creation mask is cleared:

Umask (0);
OK, the basic steps have been completed. Nginx Damon Process only steps 1,2,6, generally these 3 steps on the line, but the complexity of the case is still written according to the steps.

Let's look at an example below:

Opens a file in a child process and writes data to the file, and when certain conditions are met, the daemon exits.

void Daemon_fork () {    pid_t pid;    PID = fork ();    if (PID > 0)    {        printf ("Parent is exit\n");        Exit (0);//1th step    }    else if (PID < 0)    {        printf ("Fork is failed\n");        Exit ( -1);    }    else    {if (setsid () = =-1)//2nd Step {printf ("Setsid is failed\n");} Umask (000);//6th Step        printf ("Child is working\n"); FILE *FP = fopen ("Test.txt", "a"), if (fp = = NULL) {Kill (PID, SIGTERM);}        Do something        int i = 0;                for (;;)        {fprintf (FP, "%s", (u_char*) ("I am the Deamon two\n"));            fprintf (fp, "i =%d\n", ++i);            Sleep (), if (i >) {fclose (FP); Kill (PID, SIGTERM);}}}    

http://blog.csdn.net/xiaoliangsky/article/details/39998373

Reference:

http://blog.csdn.net/theone10211024/article/details/13774669

Http://blog.chinaunix.net/uid-25365622-id-3055635.html



Nginx Learning 13 Initial fork and Nginx Daemon Ngx_daemon

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.