Skip to content

Instantly share code, notes, and snippets.

@eljam
Last active December 11, 2015 13:28
Show Gist options
  • Save eljam/4607284 to your computer and use it in GitHub Desktop.
Save eljam/4607284 to your computer and use it in GitHub Desktop.
A simple ForkManager
<?php
/**
*
*/
class ForkManager
{
/**
* @var array Collection of pids running
*/
protected $pids = array();
/**
* @param $f
* @param array $parameters parameters to give to the closure function
* @param bool $wait if the execute have to wait
* @return bool
*/
public function execute($f, array $parameters, $wait = true)
{
$pid = pcntl_fork();
if ($pid == -1) {
new \Exception('Unable to fork current process');
} else if ($pid) {
if ($wait) {
pcntl_wait($status);
} else {
$this->pids[$pid] = $pid;
}
} else {
call_user_func_array($f, $parameters);
exit();
}
return true;
}
public function wait($nbProcessWait = 0)
{
if ($nbProcessWait > 0)
$nbProcessWait -= 1;
while (count($this->pids) > $nbProcessWait) {
$myId = pcntl_waitpid(-1, $status);
if (isset($this->pids[$myId])) {
unset($this->pids[$myId]);
}
usleep(100);
}
}
}
/**
* Usage
*/
class test
{
public function execute()
{
$forkManager = new ForkManager();
$count = 10;
while($i < $count){
$forkManager->execute(array($this, 'forkFunction'), array(), false);
//Two fork maximum
$forkManager->wait(2);
}
//kill processes
$forkManager->wait();
}
public function forkFunction()
{
echo 'ok';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment