0

I want exec() in php stop execution after given time.
eg:

exec("/usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat'",$admin_uptime)

stop his execution after 20 sec.
is it possible..??

<?php
exec("/usr/local/bin/wrun 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat'",$admin_uptime);
?>
Passerby
  • 9,715
  • 2
  • 33
  • 50

2 Answers2

0

in unix every process binds parent process. If parent dies child processes also die. So if you use this command: set_time_limit(20); your script and executed child processes killed.

nerkn
  • 1,867
  • 1
  • 20
  • 36
  • my script have more then one exec() function.I'm not kill all exec() after 20 sec. i want to give 20 sec to each exec() to complete its execution. Is it possible after 20 sec one exec() stop and 2nd exec() start its execution? –  Feb 19 '14 at 07:44
  • divide and conqure :) – nerkn Feb 19 '14 at 07:47
0

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
Jalil
  • 26
  • 1
  • 8
  • This is the second item of unattributed work I've noticed from your account. This answer [copied this one](http://stackoverflow.com/a/13636415/472495) without attribution. It's fine to copy another post, but is good practice (and good manners) to attribute it to the original author. Read more [about this here](http://meta.stackoverflow.com/a/251589/472495). – halfer Apr 26 '14 at 16:23