6

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";
}
Dan Goldstein
  • 23,436
  • 10
  • 47
  • 51

5 Answers5

6

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.

Brandon Horsley
  • 7,956
  • 1
  • 29
  • 28
  • Fixed it. It would be nice if this was documented. – Dan Goldstein Aug 20 '10 at 14:04
  • WTF?! Why isn't this told us in the PHP manual? I was investigating on this problem for hours and then it comes out that proc_open (what is explicitly suggested for more "advanced control" over custom procs) is useless. – petabyte Nov 04 '12 at 17:49
0

See this: http://www.php.net/manual/en/book.pcntl.php

Piotr Müller
  • 5,323
  • 5
  • 55
  • 82
  • Which function specifically? pcntl_exec looks like the only one that spawns something, and it stops the current process. – Dan Goldstein Aug 20 '10 at 13:29
0

Try this:

$cmdline = "sleep 5 &";
Rostyslav Dzinko
  • 39,424
  • 5
  • 49
  • 62
Matthew
  • 47,584
  • 11
  • 86
  • 98
0

Here is a great little article about creating threads. It includes a class and how to use it. http://www.alternateinterior.com/2007/05/multi-threading-strategies-in-php.html

That should get you going in the right direction.

Chuck Burgess
  • 11,600
  • 5
  • 41
  • 74
0

I think it's way "proc_open" is design to work (actually the system). You need to specify you want to disconnect with & or by actually running a shell script which will run the sub-program and return to you.

greg
  • 696
  • 1
  • 9
  • 16