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.

2
  • Why start it with a PHP script if you want it to run forever? Commented Jul 6, 2015 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. Commented Jul 6, 2015 at 20:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok that works if I run it solely with PHP. Thanks. Must be an issue with asterisks script execution then.

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.