0

I have the following exec() command with an & sign at the end so the script runs in the background. However the script is not running in the background. It's timing out in the browser after exactly 5.6 minutes. Also if i close the browser the script doesn't keep running.

 exec("/usr/local/bin/php -q /home/user/somefile.php &")

If I run the script via the command line, it does not time out. My question is how do i prevent timeout. How do i run the script in the background using exec so it's not browser dependent. What am i doing wrong and what should i look at.

2
  • stackoverflow.com/questions/45953/… Commented Nov 29, 2012 at 22:51
  • how can a shell command be "timing out in the browser" ? Commented Nov 29, 2012 at 23:04

2 Answers 2

4

exec() function handle outputs from your executed program, so I suggest you to redirect outputs to /dev/null (a virtual writable file, that automatically loose every data you write in).

Try to run :

exec("/usr/local/bin/php -q /home/gooffers/somefile.php > /dev/null 2>&1 &");

Note : 2>&1 redirects error output to standard output, and > /dev/null redirects standard output to that virtual file.

If you have still difficulties, you can create a script that just execute other scripts. exec() follows a process when it is doing a task, but releases when the task is finished. if the executed script just executes another one, the task is very quick and exec is released the same way.

Let's see an implementation. Create a exec.php that contains :

<?php

  if (count($argv) == 1)
  {
    die('You must give a script to exec...');
  }
  array_shift($argv);
  $cmd = '/usr/local/bin/php -q';
  foreach ($argv as $arg)
  {
     $cmd .= " " . escapeshellarg($arg);
  }
  exec("{$cmd} > /dev/null 2>&1 &");

?>

Now, run the following command :

exec("/usr/local/bin/php -q exec.php /home/gooffers/somefile.php > /dev/null 2>&1 &");

If you have arguments, you can give them too :

exec("/usr/local/bin/php -q exec.php /home/gooffers/somefile.php x y z > /dev/null 2>&1 &");
Sign up to request clarification or add additional context in comments.

Comments

1

You'll need to use shell_exec() instead:

shell_exec("/usr/local/bin/php -q /home/gooffers/somefile.php &");

That being said, if you have shell access, why don't you install this as a cronjob? I'm not sure why a PHP script is invoking another to run like this.

2 Comments

well, I do not see why exec() wouldn't detach a process if you're using & sign on a Linux environment.
I'm passing variables with exec. so i can't invoke it as a cron.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.