Nginx Learning 13 Initial fork and Nginx Daemon Ngx_daemon

Source: Internet
Author: User
Tags session id sessions

have been learning nginx for one months. Think more and more labored. The main reasons themselves summed up: 1 platform is based on Linux, had almost no contact with Linux, and Nginx used a lot of Linux functions. 2 is the process, and this thing has very little contact. Linux multi-process, not to mention, and now just see here, think of the unusual difficulty, this does not see the establishment of Nginx Daemon, to find 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. from/dev/null input ngx_log_error (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;}
Here is not much explanation, read the following content. You know the code above is very easy.

2fork function

A new process created by Fork is called a subprocess (child process).

The function is called once. But returned 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 are more than one child process in a process, there is no function that enables a process to obtain the process ID of all its child processes. For a sub-process, fork returns 0 to it. is because it can call Getpid () to get its own PID at any time, and can 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 the fork. The operating system replicates a child process that is completely the same as the parent process. Although the relationship between father and son. But in the operating system it seems. They are more like brotherly relationships. These 2 processes share the code space, but the data space is independent of each other, the content in the child process data space is the full copy of the parent process, the instruction pointer is also exactly the same, the child process has the parent process currently executing to the location (two process of the program counter PC value is the same, that is, The child process starts at the fork return.) But a little different, assuming fork succeeds, the return value of fork in the child process is 0, the return value of fork in the parent process is the process number of the child process, assuming 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 execution are as follows:

Parent process is runcount in parent Is:1child are run count in child is:1
From this example. To know:

1 Parent and child processes run 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 started running from the back.


The following are the relationships between parent-child processes that are specifically described 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 following is what we want to say is the child process from the parent process inherited something, what does not inherit. Another point to note is 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 descriptive descriptor of the file (note that the location of the corresponding file is shared by the parent-child process, which can cause ambiguity)
6. Run-time off (CLOSE-ON-EXEC) flag (Translator Note: The CLOSE-ON-EXEC flag can be set by Fnctl () to the file description descriptor, POSIX.1 requires that all folder flows must be closed when the EXEC function is called. More specifically, 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: The nice value is set by the Nice function, which represents the priority of the process and the smaller the value. The higher the priority level)
Process scheduling category (Scheduler Class) (Translator Note: The process scheduling category refers to the class that the process belongs to when it is scheduled in the system, different classes have different priorities, depending on the process scheduling category and the nice value, the process scheduler calculates the global priority of each process (global Process prority), priority-high processes first run)
8. Process group number
9. Conversation ID (session ID) (translator Note: The translation is taken from advanced programming, which refers to the session ID of the session to which the process belongs.) A conversation period consists of one or more process groups, and more specifically, section 9.5, "Advanced Programming"
10. Current working folder
11. Root folder (Translator Note: The root folder 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 description descriptor and folder stream (Translator Note: folder flow is created by the Opendir function, because it is read sequentially, "folder Flow")
3. The child process does not inherit the parent process's process, body (text). Data and other locked memory (locks) (Translator Note: Locked memory refers to a locked virtual memory page. After locking, 4. Do not agree to the kernel to change it if necessary (page out), specifically refer to the GNU C Library Reference Manual 2.2 Edition, 1999, 3.4.2 section)
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, user each child process total time, the system each child process total time)
6. Resource Usage (resource utilizations) set to 0
8. Block the signal set to initialize to an empty space (translator Note: The original text here does not understand, the translation according to the Fork function manual page changes slightly)
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 executes in the background.

It is independent of the control terminal and periodically performs some sort of task or waits for some event to occur. Second, the daemon must be isolated from the environment before its execution.

These environments contain file descriptive descriptors that are not closed. Control terminals, sessions, and process groups. Work folders, file creation masks, and so on.

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 run by the user terminal (typically the shell).

Steps to create the daemon:

1) Execute in background

To avoid suspending the control terminal, put the daemon into the background to run. The method is to call fork in the process to terminate the parent process and let Daemon run 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 include multiple process groups.

These process groups share a control terminal.

This control terminal is usually the login terminal of the creation process. Control terminal, logon sessions and process groups are generally inherited from the parent process. Our aim is to get rid of them. So as not to be 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 detached from the original logon session and process group. Because of the exclusive nature of the session process to the control terminal, the process is detached from the control terminal at the same time.

3) prohibit the process to open the control terminal again (this step is optional, see the situation)
Today, the process has become a non-terminal conversation leader. But it can apply again to open a control terminal. Prevents a process from opening the control terminal again by making the process no longer a session leader:

if (Pid=fork ()) exit (0); Ends the first child process. Second child process continues (second child process is no longer a conversation leader)
4) Leave open file with open Document description

The process inherits the open file descriptive descriptor from the parent process that created it. If not closed. system resources will be wasted, causing the file system where the process resides to fail to unload and cause unexpected errors.

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

5) Change the current working folder (see situation)
The file system on which the working folder resides cannot be unloaded while the process is active. It is generally necessary to change the working folder to the root folder.

For a dump core, the process of writing the execution log changes the working folder to a specific folder.

ChDir ("/tmp")

6) Reset File creation mask
The process inherits the file creation mask from the parent process that created it. It may alter 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 are complete.

Nginx Damon Process only steps 1,2,6, generally these 3 steps can be, just complex situation or follow the steps to write.

Let's look at the following example:

Opens a file in a child process and writes data to the file. When certain conditions are met. 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

References:

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.