Workerman Source code Analysis of the start-up process

Source: Internet
Author: User
Tags autoloader sigint signal

PHP has always been to the grassroots, it is simple, easy to learn, is widely used in web development, it is very unfortunate that most of the development is in simple additions and deletions, or add pdo,redis and other clients even distributed, as well as to circumvent the language itself defects. However, this is really too wronged PHP. Remember once asked walker,php what can do? He said: Anything can do! I was shocked, how could it be ... Until later always see Workerman source code, found that PHP has a lot of things not known to everyone, including multi-process (also wired), signal processing, namespace and so a lot of features. And Workerman is these rarely used features (or extension) of the synthesizer, if not to say its shortcomings, that is the shortcomings of PHP, of course, the advantages of PHP it all accounted for ~ and PHP7 released soon, Workerman will get more optimization, collocation HHVM is not in the mouth.

Workerman

Version: 3.1.8 (Linux)

Model: Gatewayworker (the worker model can be likened to it)

Note: Only the explanation part of the code, the source is given in the form of file names, you can see for yourself

Workerman originally only developed the Linux version, and win was later added, based on the command-line mode run (CLI).

Multi-process Model

Work processes, master, Gateway, and Worker,gateway are primarily used to handle IO events, to save Client link state, to send data processing requests to workers, and to work with full business logic, which is IO intensive, which is computationally intensive , between them through the network communication, Gateway and worker 22 registered communication address, so very convenient distributed deployment, if the business processing volume can simply increase the worker service.

  

They have a parent process (Master) that listens to the listener, listens for the status of the child process, sends signal to the child process, accepts commands from the terminal, signals, and so on. The parent process can be said to be the portal after the entire system starts.

Start command parsing

Since the command mode (CLI) is running (note the difference from FPM, which handles requests from the web side), there is bound to be a startup script parsing command, such as the 3.x version (daemon before default) adds a-d parameter to indicate that the daemon is running and resolves to this parameter setting self::$ Daemon = True, then fork the child process to disengage from the current process group, set up the process group leader, and so on. Here are two very important parameters $ARGC and $ARGC, the former represents the number of arguments, the latter is an array, save all parameters of the command, such as: sudo php start.php start-d, $ARGV is an array ([0]=>start.php, [1]=>start, [2]=>-d], while parsing is mainly used to $argv.

Start the following steps primarily:

    1. Contains the autoloader Autoloader, loading the startup files under each application;
    2. Set the _appinitpath root directory;
    3. Parse, initialize parameters, execute corresponding commands.

Here is a concrete implementation (workerman/worker.php):

1      Public Static functionParsecommand ()2     {3         //Check the parameters of the Run command4         Global $argv;5         $start _file=$argv[0]; 6 7         //Command8         $command=Trim($argv[1]);9         Ten         //Sub-command, currently only supports-D One         $command 2=isset($argv[2])?$argv[2]: '; A          -         //Check if the main process is running -         $master _pid= @file_get_contents(Self::$pidFile); the         $master _is_alive=$master _pid&& @posix_kill ($master _pid, 0); -         if($master _is_alive) -         { -             if($command= = = ' Start ') +             { -Self::Log("workerman[$start _file] is running "); +             } A         } at         ElseIf($command!== ' Start ' &&$command!== ' Restart ') -         { -Self::Log("workerman[$start _file] Not run "); -         } -          -         //according to the command to do the corresponding processing in         Switch($command) -         { to             //Start Workerman +              Case' Start ': -                 if($command 2= = = '-d ') the                 { *Worker::$daemonize=true; $                 }Panax Notoginseng                  Break; -             //show Workerman Run status the              Case' Status ': +                 Exit(0); A             //Restart Workerman the              Case' Restart ': +             //Stop Workeran -              Case' Stop ': $                 //want the main process to send SIGINT signal, the main process will send SIGINT signal to all child processes $                 $master _pid&& Posix_kill ($master _pid,SIGINT); -                 //Show failure interface if $timeout seconds the process does not exit -                 $timeout= 5; the                 $start _time= Time(); -                  while(1)Wuyi                 { the                     //Check if the main process is alive -                     $master _is_alive=$master _pid&& Posix_kill ($master _pid, 0); Wu                     if($master _is_alive) -                     { About                         //Check if $timeout time is exceeded $                         if( Time() -$start _time>=$timeout) -                         { -Self::Log("workerman[$start _file] Stop fail "); -                             Exit; A                         } +                         Usleep(10000); the                         Continue; -                     } $Self::Log("workerman[$start _file] Stop Success "); the                     //It's the restart command . the                     if($command= = = ' Stop ') the                     { the                         Exit(0); -                     } in                     //-D instructions are started as daemons the                     if($command 2= = = '-d ') the                     { AboutWorker::$daemonize=true; the                     } the                      Break; the                 } +                  Break; -             //Smooth Restart Workerman the              Case' Reload ':Bayi                 Exit; the         } the}

The Walker code comment is already very detailed and there are a few details here:

    • Check if the main process is alive: 17 lines of logic and operation, if the main process PID is present, send signal 0 to the process, actually do not send any information, just detect whether the process (or process group) is alive, but also detect whether the current user has permission to send system signals;
    • Why is the main process pid saved? The system starts out of the current terminal run, if you want to perform a shutdown or other command, at this time is a separate process to execute the command, if we do not even know the process PID, then who should send a signal?! So the main process PID must be saved, and the main process is responsible for listening to other sub-processes, so it is the entry that we continue to operate.
Worker::runall ()

PHP socket programming is almost the same as C, the latter on the socket has been re-wrapped, and provide interface to PHP, under PHP network programming step greatly reduced. For example: Stream_socket_server and stream_socket_client directly created the Server/client Socke (PHP has two socket operation functions). The WM uses the former extensively, and the boot process is as follows (the notes are very detailed):

1      Public Static functionRunall ()2     {3         //Initializing environment Variables4Self::init ();5         //Parse Command6Self::Parsecommand ();7         //try to run in daemon mode8Self::daemonize ();9         //Initialize all worker instances, mostly listening portsTenSelf::initworkers (); One         //initialize all signal processing functions ASelf::installsignal (); -         //Save main process pid -Self::savemasterpid (); the         //Create a child process (worker process) and run -Self::forkworkers (); -         //Display Launch Screen -Self::Displayui (); +         //attempt to redirect standard input and output -Self::resetstd (); +         //Monitor all child processes (worker processes) ASelf::monitorworkers (); at}

The following is just the key point of the process:

    1. Initialize the environment variables, such as setting the main process name, log path, initializing the timer, and so on;
    2. Parsing command line parameters, mainly used in $ARGC and $ARGC usage and C language;
    3. Generate daemons to disengage from the current terminal (two years ago most thought PHP could not do daemon, in fact, this is a mistake!). In fact, PHP in the process model of Linux is very stable, now wm in the commercial application has been very mature, a domestic company processing hundreds of millions of of the connection every day, for orders, payment calls, we can allay concerns;
    4. Initialize all worker instances (note that this is done in the main process, just generate a heap of servers and no listener is set up, the multi-process model is the listener in the sub-process, that is, Io multiplexing);
    5. Registering the signal processing function for the main process;
    6. Save the main process PID, when the system is running, we look at the system state at the terminal or perform shutdown, restart command, is through the main process to communicate, so we need to know the main process PID, we know that in the terminal to knock an executable command, but in the current terminal under the new sub-process to execute, So we need to know the main process PID to send signal to the WM main process, when the signal processing function captures the signal and executes it through a callback method.
    7. Creates a child process, setting the current process user (root). In the multi-process model, two to the child process, respectively, listen to the different server address, we in the main process just create the server and not set the listener, and do not generate a specified number of servers, because we create a process multiple times the same socket, Woker number is actually The number of sockets, that is, the number of child processes of the socket, otherwise it will error;
    8. In the child process, the server socket is registered to listen for events, using an extended event, you can implement IO multiplexing, and register the data read callback, but also register the socket connection event callback;
    9. Input/output redirection;
    10. The main process listens to the state of the subprocess and calls the Pcntl_signal_dispatch () function in an infinite loop to capture the child process exit state, which is blocked until a child process exits.

At this point, a complete boot process is done roughly, and then the server runs, waits for the socket connection event, waits for the data to read the writable event, and through the pre-registered processing function, the entire network process can be fully processed.

Conclusion

In fact, the network programming process is roughly the same, these have the standard answer, each language implementation of the approximate process is basically the same, of course, similar to the Golang Goroutine said otherwise ... Need to understand the Application layer protocol (if possible, need to unpack and packet manually), network model, TCP/UDP, interprocess communication, IO multiplexing, etc., of course, the most important is the debug ... You try to write a simple server will encounter many can not meet the pit, so the paper came to the end of shallow, I know this matter to preach.

  

Workerman Source code Analysis of the start-up process

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.