Created
April 22, 2010 14:57
-
-
Save till/375332 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
Queue_QueueController extends Zend_Controller_Action | |
{ | |
protected $workers = array(); | |
public function gearmanworkerAction() | |
{ | |
set_error_handler("queueErrorHandler"); | |
$this->setNoRender(true); | |
pcntl_signal(SIGTERM, array($this, 'signalhandler')); | |
$workerscnt = $this->_config->gearman->workers; // number of workers | |
$child = false; | |
for ($i = 0; $i < $workerscnt; $i++) { | |
$pid = pcntl_fork(); | |
if ($pid == 0) { | |
$child = true; | |
break; | |
} | |
$this->workers[] = $pid; | |
} | |
if ($child) { | |
// we are the child process, start gearman worker | |
$this->workers = array(); | |
$worker = new GearmanWorker(); | |
$worker->addServer(); | |
$worker->addFunction("foo", array($this, "foo")); | |
$worker->addFunction("bar", array($this, "bar")); | |
// etc. | |
while ($worker->work()); | |
} else { | |
pcntl_signal(SIGCHLD, array($this, 'signalhandler')); | |
while (true) { | |
sleep(1); | |
} | |
} | |
} | |
public function signalhandler($signal) | |
{ | |
switch ($signal) { | |
case SIGCHLD: | |
while (($pid = pcntl_wait($signal, WNOHANG)) > 0) { | |
foreach ($this->workers as $key => $workerpid) { | |
if ($workerpid == $pid) { | |
$newpid = pcntl_fork(); | |
if ($newpid == 0) { | |
$this->workers = array(); | |
$this->jobscount = 0; | |
return; | |
} else { | |
$this->logger->info("Restarting worker $pid, new pid $newpid."); | |
$this->workers[$key] = $newpid; | |
} | |
} | |
} | |
} | |
break; | |
case SIGTERM: | |
foreach ($this->workers as $worker) { | |
posix_kill($worker, SIGTERM); | |
} | |
exit; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment