PHP : Function Reference : Process Control Functions : pcntl_wait
federico
This a simple multi process application where you can choose
the maximun process that can run at the same time.
This is useful when you need to limit the fork of process.
When the MAXPROCESS is reached the program wait on pcntl_wait()
<?
DEFINE(MAXPROCESS,25);
for ($i=0;$i<100;$i++){
$pid = pcntl_fork();
if ($pid == -1) {
die("could not fork");
} elseif ($pid) {
echo "I'm the Parent $i\n";
$execute++;
if ($execute>=MAXPROCESS){
pcntl_wait($status);
$execute--;
}
} else {
echo "I am the child, $i pid = $pid \n";
sleep(rand(1,3));
echo "Bye Bye from $i\n";
exit;
}
}
?>
thomas dot nicolai
The code before isnt working for me cause the children are correctly started but not refreshed after they died. So keep in mind to use this instead and use the signal handler to know when a child exits to know when you have to start a new one. I added a few lines to the posting from {andy at cbeyond dot net} cause his post wasnt working for me as well (PHP5.1). Same effect like the one below.
<?php
declare(ticks = 1);
$max=5;
$child=0;
// function for signal handler
function sig_handler($signo) {
global $child;
switch ($signo) {
case SIGCHLD:
echo "SIGCHLD received\n";
$child--;
}
}
// install signal handler for dead kids
pcntl_signal(SIGCHLD, "sig_handler");
while (1){
$child++;
$pid=pcntl_fork();
if ($pid == -1) {
die("could not fork");
} else if ($pid) {
// we are the parent
if ( $child >= $max ){
pcntl_wait($status);
$child++;
}
} else {
// we are the child
echo "\t Starting new child | now we de have $child child processes\n";
// presumably doing something interesting
sleep(rand(3,5));
exit;
}
}
?>
thisisroot
Below is a simple example of forking some children and timing the total duration (useful for stress tests).
<?php
$isParent = true;
$children = array();
$start = microtime( true);
/* Fork you!
* (Sorry, I had to)
*/
$ceiling = $CONCURRENCY - 1;
for ( $i = 0; (( $i < $ceiling) && ( $isParent)); $i++) {
$pid = pcntl_fork();
if ( $pid === 0) {
$isParent = false;
} elseif ( $pid != -1) {
$children[] = $pid;
}
}
/* Process body */
echo "Do stuff here\n";
/* Cleanup */
if ( $isParent) {
$status = null;
while ( count( $children)) {
pcntl_wait( $status);
array_pop( $children);
}
echo "Completed in " . ( microtime( true) - $start) . " seconds.\n";
}
?>
|