0

I am attempting to launch sar and have it run forever via a php script. But for whatever reason it never actually launches. I have tried the following:

exec('sar -u 1 > /home/foo/foo.txt &');
exec('sar -o /home/foo/foo -u 1 > /dev/null 2>&1 &');  

However it never launches sar. If I just use:

exec('sar -u 1')

It works but it just hangs the php script. My understanding that if a program is started with exec function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream.

mcgoosh
  • 59
  • 1
  • 2
  • 11
  • Why start it with a PHP script if you want it to run forever? – Jay Blanchard Jul 06 '15 at 20:08
  • Its part of an asterisk agi script that executes a php script to start it. Then after a series of events another php script is called to stop it. In the case above though it will never actually start and run. – mcgoosh Jul 06 '15 at 20:12

1 Answers1

3

I will assume your running this on a *nix platform. To get php to run something in the background and not wait for the process to finish I would recommend 2 things: First use nohup and also redirect the output of the command to /dev/null (trash).

Example:

<?php
exec('nohup sar -u 1 > /dev/null 2>/dev/null &');

nohup means we do not send the "hang up" signal (which kills the process) when the terminal running the command closes.

> /dev/null 2>/dev/null & redirects the "normal" and "error" outputs to the blackhole /dev/null location. This allows PHP to not have to wait for the outputs of the command being called.

On another note, if you are using PHP just to call a shell command, you may want to consider other options like Ubuntu's Upstart with no PHP component--if you are using Ubuntu that is.

Community
  • 1
  • 1
DJ Sipe
  • 1,286
  • 13
  • 12
  • Ok that works if I run it solely with PHP. Thanks. Must be an issue with asterisks script execution then. – mcgoosh Jul 06 '15 at 20:34