// // pcntl_fork() : $child_pid = pcntl_fork(); if ($child_pid) { // , , exit(); } // . posix_setsid(); // ,
$baseDir = dirname(__FILE__); ini_set('error_log',$baseDir.'/error.log'); fclose(STDIN); fclose(STDOUT); fclose(STDERR); $STDIN = fopen('/dev/null', 'r'); $STDOUT = fopen($baseDir.'/application.log', 'ab'); $STDERR = fopen($baseDir.'/daemon.log', 'ab');
include 'DaemonClass.php'; $daemon = new DaemonClass(); $daemon->run();
// PHP declare(ticks=1); class DaemonClass { // public $maxProcesses = 5; // TRUE, protected $stop_server = FALSE; // protected $currentJobs = array(); public function __construct() { echo "onstructed daemon controller".PHP_EOL; // SIGTERM SIGCHLD pcntl_signal(SIGTERM, array($this, "childSignalHandler")); pcntl_signal(SIGCHLD, array($this, "childSignalHandler")); } public function run() { echo "Running daemon controller".PHP_EOL; // $stop_server TRUE, while (!$this->stop_server) { // , while(count($this->currentJobs) >= $this->maxProcesses) { echo "Maximum children allowed, waiting...".PHP_EOL; sleep(1); } $this->launchJob(); } } }
protected function launchJob() { // // pcntl_fork() // : $pid = pcntl_fork(); if ($pid == -1) { // error_log('Could not launch new job, exiting'); return FALSE; } elseif ($pid) { // $this->currentJobs[$pid] = TRUE; } else { // echo " ID ".getmypid().PHP_EOL; exit(); } return TRUE; }
public function childSignalHandler($signo, $pid = null, $status = null) { switch($signo) { case SIGTERM: // $this->stop_server = true; break; case SIGCHLD: // if (!$pid) { $pid = pcntl_waitpid(-1, $status, WNOHANG); } // while ($pid > 0) { if ($pid && isset($this->currentJobs[$pid])) { // unset($this->currentJobs[$pid]); } $pid = pcntl_waitpid(-1, $status, WNOHANG); } break; default: // } }
Source: https://habr.com/ru/post/134620/
All Articles