Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

Php Exec timeout

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 &");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...