运行环境为
Linux
,模式为CLI
DEMO
/*要创建的子进程*/
$manager = [
'work1',
'work2',
'work3',
];
/*当前进程名称*/
$status = file_exists('/proc/' . getmypid() . '/status');
$bash = '-';
if ($status) {
$bash = file('/proc/' . getmypid() . '/status', FILE_IGNORE_NEW_LINES);
$bash = reset($bash);
$bash = ltrim(substr($bash, strpos($bash, ':') + 1));
}
$title = sprintf('%s %s', $bash, $_SERVER['PWD'] . '/' . reset($_SERVER['argv']));
/*设置主进程标题*/
cli_set_process_title($title . ':manager');
/*创建子进程*/
$fork = function($key, $pool, $title) {
$pid = pcntl_fork();
if (!$pid) {
/*设置子进程名称*/
cli_set_process_title($title . ':' . $pool);
sleep(3);
print "In child $key" . PHP_EOL;
exit($key);
}
};
/*要运行多久*/
$time = time() + 10;
function quit($time)
{
if (time() > $time) {
return true;
}
return false;
}
/*SIGCHLD信号会在一个或多个子进程结束时向父进程通知*/
declare(ticks=1);
pcntl_signal(SIGCHLD, function($signal) use ($fork, $title, $time, $manager) {
switch ($signal) {
case SIGCHLD:
while (pcntl_waitpid(0, $status) != -1) {
/*pcntl_waitpid loop来让父进程及时回收全部结束的子进程*/
$status = pcntl_wexitstatus($status);
/*子进程退出后,如果不到结束时间,就重新创建子进程*/
if (quit($time) === false) {
/*是否需要重新拉起子进程*/
$fork($status, $manager[$status], $title);
}
echo "Child $status completed" . PHP_EOL;
}
exit;
}
});
/*创建子进程*/
foreach ($manager as $key => $val) {
$fork($key, $val, $title);
}
while (1) {
/*等待结束*/
sleep(1);
}
运行DEMO
[23时06分24秒] jsx@test /data/www/jsx/demo [git≠✖✱v1.2] [545f752]
✔> php demo.php
In child 0
In child 1
In child 2
Child 1 completed
Child 0 completed
Child 2 completed
In child 1
In child 0
In child 2
Child 1 completed
Child 0 completed
Child 2 completed
In child 1
In child 0
In child 2
Child 1 completed
Child 0 completed
Child 2 completed
In child 1
In child 0
In child 2
Child 1 completed
Child 0 completed
Child 2 completed
检查运行情况
[23时07分00秒] jsx@test /data/www/jsx/demo [git≠✖✱v1.2] [545f752]
✔> ps -ef | grep /demo.php
jsx 5861 25318 0 23:06 pts/4 00:00:00 php /data/www/jsx/demo/demo.php:manager
jsx 5930 5861 0 23:06 pts/4 00:00:00 php /data/www/jsx/demo/demo.php:work2
jsx 5931 5861 0 23:06 pts/4 00:00:00 php /data/www/jsx/demo/demo.php:work1
jsx 5932 5861 0 23:06 pts/4 00:00:00 php /data/www/jsx/demo/demo.php:work3
jsx 5983 1912 0 23:07 pts/0 00:00:00 grep --color=auto /demo.php