# How to fork with PHP (4 different approaches)

I thought about three (now four) different ways how to execute forks with PHP. What is the faster, maybe better solution and why?

1. PHP script included

foreach($tasks as$task) {
$pid = pcntl_fork(); if($pid == -1) {
exit("Error forking...\n");
} else if($pid == 0) { include 'worker.php'; exit(); } } while(pcntl_waitpid(0,$status) != -1);

2. PHP script executed through exec()

foreach($tasks as$task) {
$pid = pcntl_fork(); if($pid == -1) {
exit("Error forking...\n");
} else if($pid == 0) { exec('php worker.php '.$task);
exit();

}
}

while(pcntl_waitpid(0, $status) != -1);  3. PHP script executed as background command foreach($tasks as $task) {$workers[] = exec('php worker.php '.$task.' & echo$!');

}

do {
foreach($workers as$idx => $pid) { if(!posix_getpgid($pid)) {
unset($workers[$idx]);
}
}
} while(!empty(\$workers));
`

worker.php can open database connections, files, etc ...

Any good explanation would be much appreciated.

-

you have an option to do forking using pcntl yourself, or by using something more robust like PHP-Daemon on GitHub. There is also an option of background workers, which is the best option in my opinion (http://blog.anorgan.com/2013/02/22/dont-do-now-what-you-can-put-off-until-later/).

For clean and easy solution, use Gearman together with supervisord. Or http://anorgan.github.com/QuTee/ :)

-
Thanks Anorgan. I haven't tried yet, but I guess Gearman and Supervisord is the way to go :) –  Aley Feb 27 '13 at 10:16