[Linux] using PHP to write Gearman worker daemons

Source: Internet
Author: User

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 (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:
<?phpdeclare (ticks = 1);//This case would check the config file regularly, if the config file changed, it would restar  T it self//If you want to restart the daemon gracefully, give it a HUP signal//by shiqiang<[email protected]>  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"; }    }}

  

Reference: 1, Php-daemon2, IBM developers system call with me 3, how to write in PHP daemon Process4, Function exit5, PHPDaemon6, stoping Gearman worker Nicely7, Doing The worker elsewhere refer to the following fragment:
<?phpfunction handle_http_request ($address, $port) {$max _backlog = $res _content = "http/1.1 OK \ n".   "Content-length:15 \ n". "Content-type:text/plain;   Charset=utf-8 \ n ". "PHP HTTP Server Hello world!!"; $res _len = strlen ($res _content);//create, bind and listen to socketif (($socket = Socket_create (Af_inet, Sock_stream, Sol_ TCP) = = = FALSE) {echo "Create socket failed!\n"; exit;} if ((Socket_bind ($socket, $address, $port)) = = = FALSE) {echo "bind socket failed!\n"; exit;} if (Socket_listen ($socket, $max _backlog) = = = FALSE) {echo "Listen to socket failed!\n"; exit;} Loopwhile (True) {if ($accept _socket = socket_accept ($socket) = = = = FALSE) {continue;} Else{socket_write ($accept _socket, $res _content, $res _len); Socket_close ($accept _socket);}} Run as Daemon process.function run () {if (($pid 1 = pcntl_fork ()) = = = 0) {posix_setsid ();//set first child process as the SE Ssion Leader.if (($pid 2 = pcntl_fork ()) = = = 0) {handle_http_request (' 192.168.255.131 ', 10101);} Else{exit;}} Else{pcntl_wait ($status);}} Run ();? >

  

[Linux] using PHP to write Gearman worker daemons

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.