123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229 |
- <?php
- if (!defined('STATUSNET') && !defined('LACONICA')) {
- exit(1);
- }
- declare(ticks = 1);
- class ParallelizingDaemon extends Daemon
- {
- private $_children = array();
- private $_interval = 0;
- private $_max_children = 0;
- private $_debug = false;
-
- function __construct($id = null, $interval = 60, $max_children = 2,
- $debug = null)
- {
- parent::__construct(true);
- $this->_interval = $interval;
- $this->_max_children = $max_children;
- $this->_debug = $debug;
- if (isset($id)) {
- $this->set_id($id);
- }
- }
-
- function run()
- {
- if (isset($this->_debug)) {
- echo $this->name() . " - Debugging output enabled.\n";
- }
- do {
- $objects = $this->getObjects();
- foreach ($objects as $o) {
-
- $pid = pcntl_fork();
- if ($pid == -1) {
- die ($this->name() . ' - Couldn\'t fork!');
- }
- if ($pid) {
-
- if (isset($this->_debug)) {
- echo $this->name() .
- " - Forked new child - pid $pid.\n";
- }
- $this->_children[] = $pid;
- } else {
-
-
- $this->childTask($o);
- exit();
- }
-
- while (($c = pcntl_wait($status, WNOHANG OR WUNTRACED)) > 0) {
- if (isset($this->_debug)) {
- echo $this->name() . " - Child $c finished.\n";
- }
- $this->removePs($this->_children, $c);
- }
-
- if (sizeof($this->_children) >= $this->_max_children) {
- if (isset($this->_debug)) {
- echo $this->name() . " - Too many children. Waiting...\n";
- }
- if (($c = pcntl_wait($status, WUNTRACED)) > 0) {
- if (isset($this->_debug)) {
- echo $this->name() .
- " - Finished waiting for child $c.\n";
- }
- $this->removePs($this->_children, $c);
- }
- }
- }
-
- while (($c = pcntl_wait($status, WUNTRACED)) > 0) {
- if (isset($this->_debug)) {
- echo $this->name() . " - Child $c finished.\n";
- }
- $this->removePs($this->_children, $c);
- }
-
- if (isset($this->_debug)) {
- echo $this->name() . ' - Waiting ' . $this->_interval .
- " secs before running again.\n";
- }
- if ($this->_interval > 0) {
- sleep($this->_interval);
- }
- } while (true);
- }
-
- function removePs(&$plist, $ps)
- {
- for ($i = 0; $i < sizeof($plist); $i++) {
- if ($plist[$i] == $ps) {
- unset($plist[$i]);
- $plist = array_values($plist);
- break;
- }
- }
- }
-
- function getObjects()
- {
- die('Implement ParallelizingDaemon::getObjects().');
- }
-
- function childTask($object)
- {
- die("Implement ParallelizingDaemon::childTask($object).");
- }
- }
|