PHP fork - how to use pcntl_fork();

Here's a bit of PHP showing how to use pcntl_fork();

useful if you need your script to do more than one thing at the same time.

<?

declare(ticks = 1);

$max=10;
$child=0;
function sig_handler($signo) {
global $child;
switch ($signo) {
case SIGCHLD:
//echo "SIGCHLD receivedn";
// clean up zombies
$pid = pcntl_waitpid(-1, $status, WNOHANG);
$child -= 1;
//exit;
}
}

pcntl_signal(SIGCHLD, "sig_handler");

$website_scraper = new scraper();

foreach($res as $r){
while ($child >= $max) {
sleep(5); //echo " - sleep $child n";
// pcntl_waitpid(0,$status);
}
$child++;
$pid=pcntl_fork();


if ($pid==-1) {
die("Could not fork:n");
}
elseif ($pid) {
// we're in the parent fork, dont do anything
}
else {
//example of what a child process could do:
$website_scraper -> scraper("http://foo.com");
exit;
}
}
?>
Leave a Comment

Yes, send me an email when a new comment is posted.

The avatars shown next to comments are Gravatars. Click here to get a Gravatar account for free and any other site that supports it will show your avatar too!