PHP fork example

A simple example to create multi-threaded PHP application with pcntl-fork function.

Default PHP installation on OSX (Tiger and Leopard desktop and server too) missing pcntl modules, but Entropy version already contains it.

PHP source code for fork_example.php:

/**
 * PHP fork example by LouiSe@louise.hu
 */
$NUMBER_OF_THREADS = 5;

if(!function_exists('pcntl_fork')) {
	printf('Missing function pcntl_fork, compile php with "--enable-pcntl" option'."\n");
	exit();
}

$PIDs = array();

for($thread=0; $thread<$NUMBER_OF_THREADS; $thread++)
{
	$PID = pcntl_fork();
	if($PID == -1) {
	
		die('Unable to fork');
	
	} else if ($PID) {
		
		// the PARENT thread
		$PIDs[] = $PID;
	
	} else {
	
		// a CHILD thread
		echo "Thread:".$thread." PID:".getmypid()." - "; 
		
		// example function to print some text
		for($i=1;$i<10;$i++) {
			echo $i." ";
		}
		echo "\n";
		
		// exit from thread
		exit();
	}
}

// handling of normal child exit, avoid to create zombie processes
foreach($PIDs as $PID) {
	pcntl_waitpid($PID, $status);
}

Output on console:

server:~ louise$ /usr/local/php5/bin/php fork_example.php 
Thread:0 PID:31307 - 1 2 3 4 5 6 7 8 9 
Thread:1 PID:31308 - 1 2 3 4 5 6 7 8 9 
Thread:2 PID:31309 - 1 2 3 4 5 6 7 8 9 
Thread:3 PID:31310 - 1 2 3 4 5 6 7 8 9 
Thread:4 PID:31311 - 1 2 3 4 5 6 7 8 9 

Leave a Reply

Your email address will not be published. Required fields are marked *