1

I'm basically done using SSH2 with PHP. Some may already that while using it, the PHP code actually waits for all the listed commands to be executed in SSH and when everything is done, it then gives back the results. Where that is fine for the work I am doing, but I need some commands to be multi-threaded.

$cmd= MyCommand; echo $ssh->exec($cmd);

So I just want this to run in parallel 2 times. I googled some stuff but didn't get along with it. For a basic thing, I came across to this way posted by someone but it didn't work out for me.

for ($i = 0; $i < 2; $i += 1)
    {
        exec("php test_1.php $i > test.txt &");  
    //this will execute test_1.php and will leave this process executing in the background and will go to next iteration of the loop immediately without waiting the completion of the script in the test_1.php , $i  is passed as argument .
}

I tried to put it this way exec("echo $ssh->exec($cmd) $i > test.txt &"); in the loop but either it never entered the loop or the echo $ssh->exec failed. I don't really need a very neat multi-threading. Even a single second delay would do good, thank you.

HopelessN00b
  • 53,795
  • 33
  • 135
  • 209
Asad Moeen
  • 437
  • 3
  • 11
  • 22

2 Answers2

1

...apart from the fact that executing system commands has little to do with PHP, yes, executing a system command without any further preparation will cause the caller to wait for the command to finish.

Traditionally, one uses fork() for this sort of thing.

adaptr
  • 16,576
  • 23
  • 34
  • Thank and how'd I implement that ? – Asad Moeen Jul 10 '12 at 10:51
  • 2
    Seeing as this is not a PHP forum, I'd suggest SO. – adaptr Jul 10 '12 at 11:11
  • Okay I got the implementation from this same forum from someone. I have pcntl enabled in my PHP as well ( I use DirectAdmin ) but I get the error: **Call to undefined function pcntl_fork() ** Although I can see with php -ri pcntl that it's well enabled. – Asad Moeen Jul 10 '12 at 12:26
0

I found this posted by another user at ServerFault but this basically does not act as multi-threading. My $cmd3 exec command basically automatically closes after 10 seconds and these commands run for 30 seconds and are not simultaneous anyway.

$i=0;
while($i < 3)
{
$pid = pcntl_fork();

if($pid == -1)
{
    echo "Couldn't fork process";
    exit(1);
}
else
{
    if($pid)
    {
        pcntl_wait($status); 
    }
    else
    {

        echo $ssh->exec($cmd3);

    }
}
$i++;
}
Asad Moeen
  • 437
  • 3
  • 11
  • 22