Created
September 12, 2009 07:34
-
-
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
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
#!/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