Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I spawn concurrent processes with PHP?

Tags:

php

proc-open

I'm trying to spawn multiple processes at once in PHP with proc_open, but the second call won't start until the first process has ended. Here's the code I'm using:

for ($i = 0; $i < 2; $i++)
{
    $cmdline = "sleep 5";
    print $cmdline . "\n";
    $descriptors = array(0 => array('file', '/dev/null', 'r'), 
                         1 => array('file', '/dev/null', 'w'), 
                         2 => array('file', '/dev/null', 'w'));
    $proc = proc_open($cmdline, $descriptors, $pipes);
    print "opened\n";
}
like image 414
Dan Goldstein Avatar asked Aug 20 '10 13:08

Dan Goldstein


1 Answers

Others are pointing out alternatives, but your actual problem is likely the leaking of your $proc variable. I believe PHP has to keep track of this and if you are overwriting it, it will clean up for you (which means proc_close, which means waiting...)

Try not leaking the $proc value:

<?php
$procs = array();
for ($i = 0; $i < 2; $i++)
{
  $cmdline = "sleep 5";
  print $cmdline . "\n";
  $descriptors = array(0 => array('file', '/dev/null', 'r'),
    1 => array('file', '/dev/null', 'w'),
    2 => array('file', '/dev/null', 'w'));
  $procs[]= proc_open($cmdline, $descriptors, $pipes);
  print "opened\n";
}
?>

Note: This will still clean up your process handles before exiting, so all processes will have to complete first. You should use proc_close after you are done doing whatever you need to do with these (ie: read pipes, etc). If what you really want is to launch them and forget about them, that is a different solution.

like image 78
Brandon Horsley Avatar answered Oct 05 '22 06:10

Brandon Horsley