0

I have a PHP script which is run as a daemon. 8 threads run at once.

To ensure 8 threads are always running, the following PHP script is run from cron, which is in the same directory as the daemon.php script:

<?php

chdir('/root/fb');
if (file_exists('pause')) die();

exec('ps ax | grep -v grep | grep daemon.php',$output);
$output=implode("\n",$output);
$num=8-substr_count($output,'daemon.php');
if ($num>0)
 {
 for($run=0; $run<$num; $run++)
  {
  exec('php daemon.php > /dev/null 2>&1 &');
  sleep(20);
  }
 }

?>

The above will happily run the daemon.php script, but then something strange happens, and the daemon.php script itself will think it's in a different directory sometimes and not other times. Specifically, I use a lot of the exec function to execute other apps, and many of these (but not all) think they are back in the original directory and not in /root/fb.

If I execute daemon.php directly with php daemon.php from inside the directory, then this does not occur and everything works as intended.

Very off behavior. How can I set it so that the effect is exactly the same from the cron job as when the script is executed directly from inside its directory?

Alasdair
  • 13,348
  • 18
  • 82
  • 138

1 Answers1

0

Perhaps simplifying and a more defensive programming approach helps you narrow down the issue.

<?php

if (!chdir('/root/fb')) die("couldn't chdir");
file_exists('pause')) die("paused");

exec('pgrep -f "php daemon.php"',$output);
$output = implode("\n",$output);
$num = 8 - count($output);
for($run = 0; $run < $num; $run++) {
   /*exec('php daemon.php > /dev/null 2>&1 &');*/
   passthru('echo $PWD');
   sleep(20);
}

?>
j13r
  • 2,576
  • 2
  • 21
  • 28