I thought about three (now four) different ways how to execute forks with PHP. What is the faster, maybe better solution and why?
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);`
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);
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));
(additional) 4. Using Gearman
worker.php can open database connections, files, etc ...
Any good explanation would be much appreciated.