PHP – Basic Fork Example



<?
 
print "Starting main program\n";
$childs = array();
 
for ( $count = 1; $count <= 10; $count++) {
        $pid = pcntl_fork();
        if ( $pid == -1 ) {
                // Fork failed          
                echo "Fork failed\n";
                exit(1);
        } else if ( $pid ) {
                # parent
                #print "pid is $pid, parent $$\n";
                array_push($childs, $pid);
        } else  {
                # child
                sub1($count);
                exit(0);
        }
 
 
 
}
 
foreach($childs as $key => $pid) {
    pcntl_waitpid($pid, $status);
}
 
print "End of main program\n";
 
 
function sub1 ($num) {
        print "started child process for  $num\n";
        sleep(10 - $num);
        print "done with child process for $num\n";
        return $num;
}
?>