Write a daemon daemon _php tutorial in PHP

Source: Internet
Author: User

Daemon Daemon Process

This is another interesting concept, daemon in English is "elf" meaning, as we often see in the Disney animation, some can fly, some will not, often around the protagonist of the cartoon, involved saga to mention some advice, occasionally unlucky to hit the pillar, Sometimes think of some small tricks to save the protagonist from the enemy, because of this, daemon is sometimes translated as "Guardian God." Therefore, the daemon process in the country also has two kinds of translation, some people translated "wizard process", some people translated "guardian process", these two kinds of titles appear very high frequency.

Similar to the real daemon, the daemon process is accustomed to hiding itself in the eyes of people, silently contributing to the system, and sometimes referred to as a "back-office service process." The daemon process has a long lifespan, and in general, they exit when they are executed until the entire system shuts down. Almost all of the server programs, including our well-known Apache and WU-FTP, are implemented in the form of daemon processes. Many of the common commands under Linux are inetd and ftpd, with the letter D at the end referring to daemon.

Why must you use the daemon process? The interface that each system in Linux communicates with the user is called the Terminal (terminal), each process that starts from this terminal is attached to this terminal, this terminal is called the control terminal of these processes (controlling terminal), when the control terminal is closed, The corresponding process will be automatically closed. In this regard, the reader can use the X-window in the Xterm test, (each xterm is an open terminal,) we can start the application by typing a command, such as: $netscape and then we close the Xterm window, The Netscape window, which was just launched, will suddenly evaporate along with it. However, the daemon process can overcome this limitation, even if the corresponding terminal is closed, it can exist in the system for a long time, if we want to let a process live, not because of user or terminal or other changes to be affected, we must turn this process into a daemon process.

Programming rules for the daemon process

If you want to turn your process into a daemon process, we must follow these steps strictly:

1. Call fork to produce a child process while the parent process exits. All of our follow-up work is done in the child process. In doing so we can:

    • If we are executing the program from the command line, this can cause the program to complete the illusion that the shell will go back to wait for the next command;
    • The new process that has just been generated by fork must not be the head of a process group, which provides the precondition for the implementation of the 2nd step.

There is also an interesting phenomenon: because the parent process exits before the child process, it causes the child process to have no parent process and becomes an orphan process (orphan). Whenever the system discovers an orphan process, it is automatically adopted by the 1th process, so that the original child process becomes a subprocess of process 1th.

2. Invoke the SETSID system call. This is the most important step in the whole process. Its role is to create a new session and to be the leader of the session (session leader). If the calling process is the leader of a process group, the call will fail, but this is guaranteed in the 1th step. Calling Setsid has 3 functions:

    • Let the process get rid of the control of the original session;
    • Let the process get rid of the control of the original process group;
    • Let the process out of control of the original control terminal;

In short, let the calling process be completely independent and out of control of all other processes.

3. Switch the current working directory to the root directory.

If we are executing this process on a temporarily loaded file system, such as:/mnt/floppy/, the current working directory of the process will be/mnt/floppy/. The filesystem cannot be unloaded during the entire process (umount), which can be inconvenient for us regardless of whether or not we are using this file system. The workaround is to use the CHDIR system call to change the current working directory to the root directory, and no one should want to remove the root directory.

Of course, in this step, if there is a special need, we can also change the current working directory to other paths, such as/tmp.

4. Set the file permission mask to 0.

This requires calling the system call Umask, see Appendix 3. Each process inherits a file permission mask from the parent process, and when a new file is created, the mask is used to set the default access permissions for the file, masking some permissions, such as Write permissions for the general user. When another process calls the daemon program we write with exec, because we don't know what the file permission mask of that process is, it can cause some trouble when we create a new file. So, we should reset the file permission mask, we can set it to whatever value we want, but in general, everyone sets it to 0 so that it does not block any action by the user.

If your application doesn't involve creating a new file or setting up access to a file, you can simply kick the file permission mask off and skip this step.

5. Close any files that you do not need.

As with the file permission mask, our new process inherits some files that have already been opened from the parent process. These open files may never be read or written by our daemon process, but they consume system resources as well, and may cause the file system in which they reside to not be removed. It should be noted that the file descriptor is 0, 1 and 2 of three files (the concept of file descriptors will be introduced in the next chapter), that is, we often say that the input, output and error of the three files also need to be closed. It is very likely that many readers will be surprised by this, don't we need to input the output? But the fact is, after the 2nd step above, our daemon process has lost contact with the owning control terminal, the characters we enter from the terminal are not possible to reach the daemon process, and the characters that the daemon process outputs with conventional methods (such as printf) cannot be displayed on our terminal. So these three files have lost their existing value and should also be closed.

Writing daemons

In my previous article, I introduced the use of Gearman. In my project, I used PHP to write a worker that was running all the time. If according to Gearman official recommendation of the example, just a simple loop to wait for the task, there will be some problems, including: 1, the current code after the modification, how to make the code changes to take effect, 2, restart the worker, how to ensure that the current task to complete the restart.

In response to this problem, I have considered the following workaround:

    1. Each time the code is modified, the worker needs to restart manually (kill and then start). This only solves the problem of reloading the configuration file.
    2. Set in worker, the worker is restarted after a single task cycle has completed. The problem with this scheme is that it consumes more.
    3. Add an exit function to the worker and send a high-priority exit call on the client side if a worker is required to exit. This requires client mates and is not appropriate when using background class tasks.
    4. Checks to see if the file has changed in the worker, exits and restarts itself if a change occurs.
    5. Write signal control for the worker and accept the restart instruction, similar to the HTTP restart graceful directive.

Finally, the combination of 4 and 52 methods, you can implement such a daemon, if the configuration file changes, he will automatically restart, if the user received the KILL-1 PID signal, will be restarted.

The code is as follows:

  At 2011-12-04$init_md5 = md5_file (' config.php ');//Register Signal handlerpcntl_signal (SIGALRM, "Signal_handler", True    );p cntl_signal (SIGHUP, ' Signal_handler ', TRUE); $job _flag = FALSE;    Job status flag, to justify if the job has been finished$signal_flag = FALSE;    Signal status flag, to justify whether we received the Kill-1 Signalwhile (1) {$job _flag = FALSE;    JOB Status flag print "Worker start running ... n";    Sleep (5);    Print "Worker ' s task done ... n";    $flag = TRUE; JOB Status Flag AutoStart ($signal _flag);}    function Signal_handler ($signal) {global $job _flag;    Global $signal _flag; Switch ($signal) {case Sigquit:print date (' y-m-d h:i:s ', Time ()).            "Caught Signal:sigquit-no: $signal n";            Exit (0);        Break Case Sigstop:print Date (' y-m-d h:i:s ', Time ()).            "Caught Signal:sigstop-no: $signal n";        Break Case Sighup:print Date (' y-m-d h:i:S ', Time ()).            "Caught Signal:sighup-no: $signal n";            if ($flag = = = True) {AutoStart (true);            }else{$signal _flag = TRUE;        } break; Case Sigalrm:print Date (' y-m-d h:i:s ', Time ()).            "Caught Signal:sigalrm-no: $signal n";            Pcntl_exec ('/bin/ls ');            Pcntl_alarm (5);        Break    Default:break;    }}function AutoStart ($signal = FALSE, $filename = ' config.php ') {global $init _md5; if ($signal | | md5_file ($filename)! = $init _md5) {print "The config file has been changed, we is going to Resta        Rt. N ";        $pid = Pcntl_fork ();        if ($pid = =-1) {print "Fork error n";            }else if ($pid > 0) {print "Parent exit n";        Exit (0);            }else{$init _md5 = md5_file ($filename);        Print "Child continue to run N"; }}}?>

http://www.bkjia.com/PHPjc/752556.html www.bkjia.com true http://www.bkjia.com/PHPjc/752556.html techarticle Daemon Daemon This is another interesting concept, daemon in English is the meaning of "elves", as we often see in the Disney animation, some can fly, some will not, after ...

  • 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.