Skip to content

Instantly share code, notes, and snippets.

@axgle
Created November 27, 2009 03:48
Show Gist options
  • Save axgle/243815 to your computer and use it in GitHub Desktop.
Save axgle/243815 to your computer and use it in GitHub Desktop.
<?php
declare (ticks=1);
class MTDaemon2{
var $max_threads = 10;
var $idlesleeptime = 3;
var $run=true;
var $slot=0;
function __construct($threads = null, $idlesleeptime = null){
if ($threads) {
$this->max_threads=$threads;
}
if ($idlesleeptime) {
$this->idlesleeptime=$idlesleeptime;
}
$pid=pcntl_fork();
if($pid>0){
exit;
}
pcntl_signal(SIGCHLD, array(&$this,'signal_handler'));
}
function signal_handler($signo){
if($signo==SIGCHLD) {
$this->slot--;
//$this->info("CHILD received:{$this->slot}");
}
}
function handle(){
$time=date("Y-m-d H:i:s");
$this->info($_SERVER['argv'][0].':['.$time.']:Starting daemon2 with '.$this->max_threads." slots");
while($this->run){
if ($this->slot>=$this->max_threads) {
pcntl_wait(&$status);
}
try {
$next = &$this->getNext($this->slot);
} catch( Exception $e ) {
$this->info('getNext() method: '.$e->getMessage());
continue;
}
if ($next==null) {
continue;
}
if ($this->run==false) {
break;
}
$pid=pcntl_fork();
if($pid==-1){
$this->info("fork:pid=-1");
}elseif($pid){
$this->slot++;
//continue;
} else {
try {
$this->run($next,$this->slot);
} catch( Exception $e ) {
echo('run() method: '.$e->getMessage());
}
exit;
}
}
$time=date("Y-m-d H:i:s");
$this->info($_SERVER['argv'][0].":[{$time}]: daemon exited");
}
function run($next,$slot){
}
function getNext($slot){
}
function lock() {
}
/*
*
*/
function unlock() {
}
function info($str){
echo $str."\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment