Use PHP script to write daemon program _php tutorial

Source: Internet
Author: User
Tags signal handler
What is the 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:

1.1 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;

1.2 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. Call Setsid system call. This is the most important step in the whole process. Setsid's introduction is shown in Appendix 2, which is the role of creating a new session and being 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:

2.1 Let the process get rid of the control of the original session;

2.2 Let the process get rid of the control of the original process group;

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

For the use of ChDir, see Appendix 1.

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 control terminal, we can not reach the daemon process from the terminal input characters, daemon process with the conventional method ( Characters such as printf) cannot be displayed on our terminal. So these three files have lost their existing value and should also be closed.

Using PHP to write Gearman worker 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. After each revision of the code, the worker needs to be restarted manually (first kill and then start). This only solves the problem of reloading the configuration file.

2, set in the worker, after a single task cycle is completed, the worker is restarted. 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. Check that the file changes in the worker, and if it changes, exit and restart itself.

5, write the signal control for the worker, accept the restart instruction, similar to the HTTP restart graceful instruction.

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:

Copy to ClipboardWhat to refer to: [www.bkjia.com]
DECLARE (ticks = 1);
This case would check the config file regularly, if the config file changed, it would restart it self
If you want to restart the daemon gracefully, give it a HUP signal
by Shiqiang At 2011-12-04

$init _md5 = md5_file (' config.php ');

Register Signal Handler
Pcntl_signal (SIGALRM, "Signal_handler", true);
Pcntl_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 Signal

while (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 restart. \ 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";
}
}
}

(Source of this article: Blog Park, author: The World of the Little Wolf)

http://www.bkjia.com/PHPjc/363858.html www.bkjia.com true http://www.bkjia.com/PHPjc/363858.html techarticle What is the daemon process this is another interesting concept, daemon in English is the meaning of the 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.