Skip to content

Instantly share code, notes, and snippets.

@eugenepyvovarov
Created September 12, 2009 07:34
Show Gist options
  • Save eugenepyvovarov/185748 to your computer and use it in GitHub Desktop.
Save eugenepyvovarov/185748 to your computer and use it in GitHub Desktop.
to run script you need first to create lock folder in the same place
#!/usr/bin/env php
<?php
declare(ticks=1);
// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
$children = array();
$max_count = 5;
for($i=0;$i<10;$i++) {
$amount = count(scandir(dirname(__FILE__).'/lock')) - 2;
if($amount < $max_count){
print 'creating new thred '. "\r\n";
$pid = pcntl_fork();
exec('touch '.dirname(__FILE__).'/lock/'.$i);
if ($pid == -1) {
die("could not fork");
} else if ($pid) {
//exit(); // we are the parent
$children[$i] = $pid;
continue;
} else {
// we are the child
$sl = rand(15,19);
sleep($sl);
echo $sl.'blablabla'. $i . "\r\n";
exec('rm '.dirname(__FILE__).'/lock/'.$i);
print "closed thread \r\n";
exit(0);
}
} else {
$i--;
}
}
foreach ($children as $key => $pid) {
// We are the parent, so we shall wait till all children will die.
// Otherwise there will be bunch of zombies.
pcntl_waitpid($pid, $status);
}
exit(0);
function sig_handler($signo) {
switch ($signo) {
case SIGTERM:
// handle shutdown tasks
exit;
break;
case SIGHUP:
// handle restart tasks
break;
default:
// handle all other signals
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment