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));
    

(additional) 4. Using Gearman

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

Any good explanation would be much appreciated.

share|improve this question

1 Answer

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/ :)

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.