Write a Daemon in PHP

Source: Internet
Author: User

Daemon

This is another interesting concept. In English, daemon refers to "Genie", just like what we often see in Disney animations. Some of them will fly, and some will not, I often turn around the cartoon hero and give some advice in the dark. Sometimes I am unlucky to hit the pillar. Sometimes I want to come up with some small tricks to save the hero from the enemy. For this reason, daemon is sometimes translated as "patron saint ". Therefore, the daemon process has two translation methods in China. Some translate "Genie process" and some translate "daemon process", which are frequently used.

Similar to the real daemon process, the daemon process is also used to hiding itself out of sight and silently contributing to the system. Sometimes they are called "background service processes ". Daemon processes have a long life cycle. Generally, they exit from execution until the entire system is shut down. Almost all server programs, including well-known Apache and wu-FTP, are implemented in the form of a daemon process. Many common commands in Linux, such as inetd and ftpd, use the letter d at the end of daemon.

Why must the daemon process be used? In Linux, the interface for communication between each system and users is called terminal. Every process starting from this terminal is attached to this terminal, this terminal is called the control terminal of these processes. When the control terminal is closed, the corresponding process is automatically closed. In this case, you can use the XTerm in X-Window to experiment with it. (each XTerm is an open terminal.) You can run the following command to start the application: $ netscape then we close the XTerm window, and the newly started netscape window will also evaporate. However, the daemon process can break through this restriction. Even if the corresponding terminal is closed, it can survive for a long time in the system. If we want a process to survive for a hundred years, without being affected by user, terminal, or other changes, you must turn this process into a daemon process.

Daemon process programming rules

To change your process to a daemon process, follow these steps:

1. Call fork to generate a child process, and the parent process exits. All subsequent work is completed in the sub-process. In this way, we can:

  • If we execute the program from the command line, this may lead to the illusion that the program has been executed, shell will go back and wait for the next command;
  • The new process generated through fork will not be the leader of a process group, which provides a prerequisite for the implementation of step 1.

In this case, a very interesting phenomenon occurs: because the parent process has exited before the child process, it will cause the child process to have no parent process and become an orphan process (orphan ). Every time the system finds an orphan process, it will be automatically adopted by process 1, so that the original child process will become the child process of process 1.

2. Call the setsid system call. This is the most important step in the process. It is used to create a new session and act as the session leader ). If the calling process is the leader of a process group, the call will fail, but this is guaranteed in step 1. Calling setsid has three functions:

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

In short, the calling process is completely independent from the control of all other processes.

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

If we execute this process on a temporary file system, such as/mnt/floppy/, the current working directory of the process will be/mnt/floppy /. The file system cannot be detached (umount) during the entire process, and whether or not we are using this file system, this will cause us a lot of inconvenience. The solution is to use the chdir system call to change the current working directory to the root directory. No one wants to unload the root directory.

Of course, in this step, if there are special needs, we can also change the current working directory to another path, such as/tmp.

4. Set the File Permission mask to 0.

This requires that the system call umask be called. See Appendix 3. Each process inherits a File Permission mask from the parent process. When a new file is created, this mask is used to set the default access permissions for the file and block some permissions, for example, the write permission of a general user. When another process uses exec to call our daemon program, because we do not know what the File Permission mask of the process is, it will cause some trouble when we create a new file. Therefore, we should re-set the File Permission mask. We can set it to any value we want, but generally we set it to 0, it does not block any user operations.

If your application does not involve creating new files or setting file access permissions, you can also kick off the File Permission mask and skip this step.

5. Close all unnecessary files.

Like the File Permission mask, our new process will inherit some opened files from the parent process. These opened files may never be read or written by our daemon process, but they consume the same system resources and may cause the file system to be unable to be detached. It should be noted that the file descriptor is 0, 1, and 2 (the concept of the file descriptor will be introduced in the next chapter ), that is to say, the input, output, and error files also need to be closed. Many readers may wonder this. Do we not need input or output? But the fact is that after Step 1 above, our daemon process has lost contact with the control terminal, and the characters we input from the terminal cannot reach the daemon process, the daemon process output characters using conventional methods (such as printf) cannot be displayed on our terminal. Therefore, these three files have lost value and should be closed.

Write daemon

In my previous articles, I introduced the use of Gearman. In my project, I used PHP to write a Worker that has been running all the time. If you follow the example officially recommended by Gearman, it is just a simple loop to wait for the task, there will be some problems, including: 1. How to Make the code modification take effect after the code is modified; 2. How to ensure that the current task is restarted after the Worker is restarted.

To solve this problem, I have considered the following solutions:

  1. After the code is modified, the Worker needs to be manually restarted (killed first and then started ). This can only solve the problem of re-loading the configuration file.
  2. Set in Worker. After a single task loop is completed, restart the Worker. The problem with this solution is that it consumes a lot.
  3. Add an exit function to the Worker. If the Worker needs to exit, send an exit call with a higher priority on the Client side. This requires the cooperation of the client and is not suitable for background tasks.
  4. Check whether the file changes in the Worker. If the file changes, exit and restart itself.
  5. Write signal control for Worker and receive restart commands, similar to the http restart graceful command.

Finally, a Daemon can be implemented by combining the 4 and 5 methods. If the configuration file changes, it will automatically restart. If the user's kill-1 pid signal is received, it also restarts.

The Code is as follows:

<?phpdeclare( ticks = 1 );// This case will check the config file regularly, if the config file changed, it will restart it self// If you want to restart the daemon gracefully, give it a HUP signal// by shiqiang<cocowool@gmail.com> at 2011-12-04$init_md5 = md5_file( 'config.php');// register signal handlerpcntl_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 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 are 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";        }    }}?>

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.