forked from walkor/workerman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Worker.php
1555 lines (1418 loc) · 46 KB
/
Worker.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* This file is part of workerman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Workerman;
require_once __DIR__ . '/Lib/Constants.php';
use Workerman\Events\EventInterface;
use Workerman\Connection\ConnectionInterface;
use Workerman\Connection\TcpConnection;
use Workerman\Connection\UdpConnection;
use Workerman\Lib\Timer;
use Exception;
/**
* Worker class
* A container for listening ports
*/
class Worker
{
/**
* Version.
*
* @var string
*/
const VERSION = '3.3.1';
/**
* Status starting.
*
* @var int
*/
const STATUS_STARTING = 1;
/**
* Status running.
*
* @var int
*/
const STATUS_RUNNING = 2;
/**
* Status shutdown.
*
* @var int
*/
const STATUS_SHUTDOWN = 4;
/**
* Status reloading.
*
* @var int
*/
const STATUS_RELOADING = 8;
/**
* After sending the restart command to the child process KILL_WORKER_TIMER_TIME seconds,
* if the process is still living then forced to kill.
*
* @var int
*/
const KILL_WORKER_TIMER_TIME = 2;
/**
* Default backlog. Backlog is the maximum length of the queue of pending connections.
*
* @var int
*/
const DEFAUL_BACKLOG = 1024;
/**
* Max udp package size.
*
* @var int
*/
const MAX_UDP_PACKAGE_SIZE = 65535;
/**
* Worker id.
*
* @var int
*/
public $id = 0;
/**
* Name of the worker processes.
*
* @var string
*/
public $name = 'none';
/**
* Number of worker processes.
*
* @var int
*/
public $count = 1;
/**
* Unix user of processes, needs appropriate privileges (usually root).
*
* @var string
*/
public $user = '';
/**
* Unix group of processes, needs appropriate privileges (usually root).
*
* @var string
*/
public $group = '';
/**
* reloadable.
*
* @var bool
*/
public $reloadable = true;
/**
* reuse port.
*
* @var bool
*/
public $reusePort = false;
/**
* Emitted when worker processes start.
*
* @var callback
*/
public $onWorkerStart = null;
/**
* Emitted when a socket connection is successfully established.
*
* @var callback
*/
public $onConnect = null;
/**
* Emitted when data is received.
*
* @var callback
*/
public $onMessage = null;
/**
* Emitted when the other end of the socket sends a FIN packet.
*
* @var callback
*/
public $onClose = null;
/**
* Emitted when an error occurs with connection.
*
* @var callback
*/
public $onError = null;
/**
* Emitted when the send buffer becomes full.
*
* @var callback
*/
public $onBufferFull = null;
/**
* Emitted when the send buffer becomes empty.
*
* @var callback
*/
public $onBufferDrain = null;
/**
* Emitted when worker processes stoped.
*
* @var callback
*/
public $onWorkerStop = null;
/**
* Emitted when worker processes get reload command.
*
* @var callback
*/
public $onWorkerReload = null;
/**
* Transport layer protocol.
*
* @var string
*/
public $transport = 'tcp';
/**
* Store all connections of clients.
*
* @var array
*/
public $connections = array();
/**
* Application layer protocol.
*
* @var Protocols\ProtocolInterface
*/
public $protocol = '';
/**
* Root path for autoload.
*
* @var string
*/
protected $_autoloadRootPath = '';
/**
* Daemonize.
*
* @var bool
*/
public static $daemonize = false;
/**
* Stdout file.
*
* @var string
*/
public static $stdoutFile = '/dev/null';
/**
* The file to store master process PID.
*
* @var string
*/
public static $pidFile = '';
/**
* Log file.
*
* @var mixed
*/
public static $logFile = '';
/**
* Global event loop.
*
* @var Events\EventInterface
*/
public static $globalEvent = null;
/**
* The PID of master process.
*
* @var int
*/
protected static $_masterPid = 0;
/**
* Listening socket.
*
* @var resource
*/
protected $_mainSocket = null;
/**
* Socket name. The format is like this http://0.0.0.0:80 .
*
* @var string
*/
protected $_socketName = '';
/**
* Context of socket.
*
* @var resource
*/
protected $_context = null;
/**
* All worker instances.
*
* @var array
*/
protected static $_workers = array();
/**
* All worker porcesses pid.
* The format is like this [worker_id=>[pid=>pid, pid=>pid, ..], ..]
*
* @var array
*/
protected static $_pidMap = array();
/**
* All worker processes waiting for restart.
* The format is like this [pid=>pid, pid=>pid].
*
* @var array
*/
protected static $_pidsToRestart = array();
/**
* Mapping from PID to worker process ID.
* The format is like this [worker_id=>[0=>$pid, 1=>$pid, ..], ..].
*
* @var array
*/
protected static $_idMap = array();
/**
* Current status.
*
* @var int
*/
protected static $_status = self::STATUS_STARTING;
/**
* Maximum length of the worker names.
*
* @var int
*/
protected static $_maxWorkerNameLength = 12;
/**
* Maximum length of the socket names.
*
* @var int
*/
protected static $_maxSocketNameLength = 12;
/**
* Maximum length of the process user names.
*
* @var int
*/
protected static $_maxUserNameLength = 12;
/**
* The file to store status info of current worker process.
*
* @var string
*/
protected static $_statisticsFile = '';
/**
* Start file.
*
* @var string
*/
protected static $_startFile = '';
/**
* Status info of current worker process.
*
* @var array
*/
protected static $_globalStatistics = array(
'start_timestamp' => 0,
'worker_exit_info' => array()
);
/**
* Available event loops.
*
* @var array
*/
protected static $_availableEventLoops = array(
'libevent',
'event',
'ev'
);
/**
* Current eventLoop name.
*
* @var string
*/
protected static $_eventLoopName = 'select';
/**
* PHP built-in protocols.
*
* @var array
*/
protected static $_builtinTransports = array(
'tcp' => 'tcp',
'udp' => 'udp',
'unix' => 'unix',
'ssl' => 'tcp',
'tsl' => 'tcp',
'sslv2' => 'tcp',
'sslv3' => 'tcp',
'tls' => 'tcp'
);
/**
* Run all worker instances.
*
* @return void
*/
public static function runAll()
{
self::checkSapiEnv();
self::init();
self::parseCommand();
self::daemonize();
self::initWorkers();
self::installSignal();
self::saveMasterPid();
self::forkWorkers();
self::displayUI();
self::resetStd();
self::monitorWorkers();
}
/**
* Check sapi.
*
* @return void
*/
protected static function checkSapiEnv()
{
// Only for cli.
if (php_sapi_name() != "cli") {
exit("only run in command line mode \n");
}
}
/**
* Init.
*
* @return void
*/
protected static function init()
{
// Start file.
$backtrace = debug_backtrace();
self::$_startFile = $backtrace[count($backtrace) - 1]['file'];
// Pid file.
if (empty(self::$pidFile)) {
self::$pidFile = __DIR__ . "/../" . str_replace('/', '_', self::$_startFile) . ".pid";
}
// Log file.
if (empty(self::$logFile)) {
self::$logFile = __DIR__ . '/../workerman.log';
}
touch(self::$logFile);
chmod(self::$logFile, 0622);
// State.
self::$_status = self::STATUS_STARTING;
// For statistics.
self::$_globalStatistics['start_timestamp'] = time();
self::$_statisticsFile = sys_get_temp_dir() . '/workerman.status';
// Process title.
self::setProcessTitle('WorkerMan: master process start_file=' . self::$_startFile);
// Init data for worker id.
self::initId();
// Timer init.
Timer::init();
}
/**
* Init All worker instances.
*
* @return void
*/
protected static function initWorkers()
{
foreach (self::$_workers as $worker) {
// Worker name.
if (empty($worker->name)) {
$worker->name = 'none';
}
// Get maximum length of worker name.
$worker_name_length = strlen($worker->name);
if (self::$_maxWorkerNameLength < $worker_name_length) {
self::$_maxWorkerNameLength = $worker_name_length;
}
// Get maximum length of socket name.
$socket_name_length = strlen($worker->getSocketName());
if (self::$_maxSocketNameLength < $socket_name_length) {
self::$_maxSocketNameLength = $socket_name_length;
}
// Get unix user of the worker process.
if (empty($worker->user)) {
$worker->user = self::getCurrentUser();
} else {
if (posix_getuid() !== 0 && $worker->user != self::getCurrentUser()) {
self::log('Warning: You must have the root privileges to change uid and gid.');
}
}
// Get maximum length of unix user name.
$user_name_length = strlen($worker->user);
if (self::$_maxUserNameLength < $user_name_length) {
self::$_maxUserNameLength = $user_name_length;
}
// Listen.
if (!$worker->reusePort) {
$worker->listen();
}
}
}
/**
* Init idMap.
* return void
*/
protected static function initId()
{
foreach (self::$_workers as $worker_id => $worker) {
self::$_idMap[$worker_id] = array_fill(0, $worker->count, 0);
}
}
/**
* Get unix user of current porcess.
*
* @return string
*/
protected static function getCurrentUser()
{
$user_info = posix_getpwuid(posix_getuid());
return $user_info['name'];
}
/**
* Display staring UI.
*
* @return void
*/
protected static function displayUI()
{
echo "\033[1A\n\033[K-----------------------\033[47;30m WORKERMAN \033[0m-----------------------------\n\033[0m";
echo 'Workerman version:', Worker::VERSION, " PHP version:", PHP_VERSION, "\n";
echo "------------------------\033[47;30m WORKERS \033[0m-------------------------------\n";
echo "\033[47;30muser\033[0m", str_pad('',
self::$_maxUserNameLength + 2 - strlen('user')), "\033[47;30mworker\033[0m", str_pad('',
self::$_maxWorkerNameLength + 2 - strlen('worker')), "\033[47;30mlisten\033[0m", str_pad('',
self::$_maxSocketNameLength + 2 - strlen('listen')), "\033[47;30mprocesses\033[0m \033[47;30m", "status\033[0m\n";
foreach (self::$_workers as $worker) {
echo str_pad($worker->user, self::$_maxUserNameLength + 2), str_pad($worker->name,
self::$_maxWorkerNameLength + 2), str_pad($worker->getSocketName(),
self::$_maxSocketNameLength + 2), str_pad(' ' . $worker->count, 9), " \033[32;40m [OK] \033[0m\n";;
}
echo "----------------------------------------------------------------\n";
if (self::$daemonize) {
global $argv;
$start_file = $argv[0];
echo "Input \"php $start_file stop\" to quit. Start success.\n";
} else {
echo "Press Ctrl-C to quit. Start success.\n";
}
}
/**
* Parse command.
* php yourfile.php start | stop | restart | reload | status
*
* @return void
*/
protected static function parseCommand()
{
global $argv;
// Check argv;
$start_file = $argv[0];
if (!isset($argv[1])) {
exit("Usage: php yourfile.php {start|stop|restart|reload|status|kill}\n");
}
// Get command.
$command = trim($argv[1]);
$command2 = isset($argv[2]) ? $argv[2] : '';
// Start command.
$mode = '';
if ($command === 'start') {
if ($command2 === '-d') {
$mode = 'in DAEMON mode';
} else {
$mode = 'in DEBUG mode';
}
}
self::log("Workerman[$start_file] $command $mode");
// Get master process PID.
$master_pid = @file_get_contents(self::$pidFile);
$master_is_alive = $master_pid && @posix_kill($master_pid, 0);
// Master is still alive?
if ($master_is_alive) {
if ($command === 'start') {
self::log("Workerman[$start_file] already running");
exit;
}
} elseif ($command !== 'start' && $command !== 'restart') {
self::log("Workerman[$start_file] not run");
}
// Execure command.
switch ($command) {
case 'kill':
exec("ps aux | grep $start_file | grep -v grep | awk '{print $2}' |xargs kill -SIGINT");
exec("ps aux | grep $start_file | grep -v grep | awk '{print $2}' |xargs kill -SIGKILL");
break;
case 'start':
if ($command2 === '-d') {
Worker::$daemonize = true;
}
break;
case 'status':
if (is_file(self::$_statisticsFile)) {
@unlink(self::$_statisticsFile);
}
// Master process will send status signal to all child processes.
posix_kill($master_pid, SIGUSR2);
// Waiting amoment.
usleep(100000);
// Display statisitcs data from a disk file.
@readfile(self::$_statisticsFile);
exit(0);
case 'restart':
case 'stop':
self::log("Workerman[$start_file] is stoping ...");
// Send stop signal to master process.
$master_pid && posix_kill($master_pid, SIGINT);
// Timeout.
$timeout = 5;
$start_time = time();
// Check master process is still alive?
while (1) {
$master_is_alive = $master_pid && posix_kill($master_pid, 0);
if ($master_is_alive) {
// Timeout?
if (time() - $start_time >= $timeout) {
self::log("Workerman[$start_file] stop fail");
exit;
}
// Waiting amoment.
usleep(10000);
continue;
}
// Stop success.
self::log("Workerman[$start_file] stop success");
if ($command === 'stop') {
exit(0);
}
if ($command2 === '-d') {
Worker::$daemonize = true;
}
break;
}
break;
case 'reload':
posix_kill($master_pid, SIGUSR1);
self::log("Workerman[$start_file] reload");
exit;
default :
exit("Usage: php yourfile.php {start|stop|restart|reload|status|kill}\n");
}
}
/**
* Install signal handler.
*
* @return void
*/
protected static function installSignal()
{
// stop
pcntl_signal(SIGINT, array('\Workerman\Worker', 'signalHandler'), false);
// reload
pcntl_signal(SIGUSR1, array('\Workerman\Worker', 'signalHandler'), false);
// status
pcntl_signal(SIGUSR2, array('\Workerman\Worker', 'signalHandler'), false);
// ignore
pcntl_signal(SIGPIPE, SIG_IGN, false);
}
/**
* Reinstall signal handler.
*
* @return void
*/
protected static function reinstallSignal()
{
// uninstall stop signal handler
pcntl_signal(SIGINT, SIG_IGN, false);
// uninstall reload signal handler
pcntl_signal(SIGUSR1, SIG_IGN, false);
// uninstall status signal handler
pcntl_signal(SIGUSR2, SIG_IGN, false);
// reinstall stop signal handler
self::$globalEvent->add(SIGINT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
// uninstall reload signal handler
self::$globalEvent->add(SIGUSR1, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
// uninstall status signal handler
self::$globalEvent->add(SIGUSR2, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
}
/**
* Signal hander.
*
* @param int $signal
*/
public static function signalHandler($signal)
{
switch ($signal) {
// Stop.
case SIGINT:
self::stopAll();
break;
// Reload.
case SIGUSR1:
self::$_pidsToRestart = self::getAllWorkerPids();
self::reload();
break;
// Show status.
case SIGUSR2:
self::writeStatisticsToStatusFile();
break;
}
}
/**
* Run as deamon mode.
*
* @throws Exception
*/
protected static function daemonize()
{
if (!self::$daemonize) {
return;
}
umask(0);
$pid = pcntl_fork();
if (-1 === $pid) {
throw new Exception('fork fail');
} elseif ($pid > 0) {
exit(0);
}
if (-1 === posix_setsid()) {
throw new Exception("setsid fail");
}
// Fork again avoid SVR4 system regain the control of terminal.
$pid = pcntl_fork();
if (-1 === $pid) {
throw new Exception("fork fail");
} elseif (0 !== $pid) {
exit(0);
}
}
/**
* Redirect standard input and output.
*
* @throws Exception
*/
protected static function resetStd()
{
if (!self::$daemonize) {
return;
}
global $STDOUT, $STDERR;
$handle = fopen(self::$stdoutFile, "a");
if ($handle) {
unset($handle);
@fclose(STDOUT);
@fclose(STDERR);
$STDOUT = fopen(self::$stdoutFile, "a");
$STDERR = fopen(self::$stdoutFile, "a");
} else {
throw new Exception('can not open stdoutFile ' . self::$stdoutFile);
}
}
/**
* Save pid.
*
* @throws Exception
*/
protected static function saveMasterPid()
{
self::$_masterPid = posix_getpid();
if (false === @file_put_contents(self::$pidFile, self::$_masterPid)) {
throw new Exception('can not save pid to ' . self::$pidFile);
}
}
/**
* Get event loop name.
*
* @return string
*/
protected static function getEventLoopName()
{
foreach (self::$_availableEventLoops as $name) {
if (extension_loaded($name)) {
self::$_eventLoopName = $name;
break;
}
}
return self::$_eventLoopName;
}
/**
* Get all pids of worker processes.
*
* @return array
*/
protected static function getAllWorkerPids()
{
$pid_array = array();
foreach (self::$_pidMap as $worker_pid_array) {
foreach ($worker_pid_array as $worker_pid) {
$pid_array[$worker_pid] = $worker_pid;
}
}
return $pid_array;
}
/**
* Fork some worker processes.
*
* @return void
*/
protected static function forkWorkers()
{
foreach (self::$_workers as $worker) {
if (self::$_status === self::STATUS_STARTING) {
if (empty($worker->name)) {
$worker->name = $worker->getSocketName();
}
$worker_name_length = strlen($worker->name);
if (self::$_maxWorkerNameLength < $worker_name_length) {
self::$_maxWorkerNameLength = $worker_name_length;
}
}
while (count(self::$_pidMap[$worker->workerId]) < $worker->count) {
static::forkOneWorker($worker);
}
}
}
/**
* Fork one worker process.
*
* @param Worker $worker
* @throws Exception
*/
protected static function forkOneWorker($worker)
{
$pid = pcntl_fork();
// Get available worker id.
$id = self::getId($worker->workerId, 0);
// For master process.
if ($pid > 0) {
self::$_pidMap[$worker->workerId][$pid] = $pid;
self::$_idMap[$worker->workerId][$id] = $pid;
} // For child processes.
elseif (0 === $pid) {
if ($worker->reusePort) {
$worker->listen();
}
if (self::$_status === self::STATUS_STARTING) {
self::resetStd();
}
self::$_pidMap = array();
self::$_workers = array($worker->workerId => $worker);
Timer::delAll();
self::setProcessTitle('WorkerMan: worker process ' . $worker->name . ' ' . $worker->getSocketName());
$worker->setUserAndGroup();
$worker->id = $id;
$worker->run();
exit(250);
} else {
throw new Exception("forkOneWorker fail");
}
}
/**
* Get worker id.
*
* @param int $worker_id
* @param int $pid
*/
protected static function getId($worker_id, $pid)
{
$id = array_search($pid, self::$_idMap[$worker_id]);
if ($id === false) {
echo "getId fail\n";
}
return $id;
}
/**
* Set unix user and group for current process.
*
* @return void
*/
public function setUserAndGroup()
{
// Get uid.
$user_info = posix_getpwnam($this->user);
if (!$user_info) {
self::log("Warning: User {$this->user} not exsits");
return;
}
$uid = $user_info['uid'];
// Get gid.
if ($this->group) {
$group_info = posix_getgrnam($this->group);
if (!$group_info) {
self::log("Warning: Group {$this->group} not exsits");
return;
}
$gid = $group_info['gid'];
} else {
$gid = $user_info['gid'];
}
// Set uid and gid.
if ($uid != posix_getuid() || $gid != posix_getgid()) {
if (!posix_setgid($gid) || !posix_initgroups($user_info['name'], $gid) || !posix_setuid($uid)) {
self::log("Warning: change gid or uid fail.");
}
}
}
/**
* Set process name.
*
* @param string $title
* @return void
*/
protected static function setProcessTitle($title)
{
// >=php 5.5
if (function_exists('cli_set_process_title')) {
@cli_set_process_title($title);
} // Need proctitle when php<=5.5 .
elseif (extension_loaded('proctitle') && function_exists('setproctitle')) {
@setproctitle($title);
}
}
/**
* Monitor all child processes.
*
* @return void
*/
protected static function monitorWorkers()
{
self::$_status = self::STATUS_RUNNING;
while (1) {
// Calls signal handlers for pending signals.
pcntl_signal_dispatch();
// Suspends execution of the current process until a child has exited, or until a signal is delivered
$status = 0;
$pid = pcntl_wait($status, WUNTRACED);
// Calls signal handlers for pending signals again.
pcntl_signal_dispatch();
// If a child has already exited.
if ($pid > 0) {
// Find out witch worker process exited.
foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
if (isset($worker_pid_array[$pid])) {
$worker = self::$_workers[$worker_id];
// Exit status.
if ($status !== 0) {
self::log("worker[" . $worker->name . ":$pid] exit with status $status");
}
// For Statistics.
if (!isset(self::$_globalStatistics['worker_exit_info'][$worker_id][$status])) {
self::$_globalStatistics['worker_exit_info'][$worker_id][$status] = 0;