I am trying to send a SIGHUP signal to an external process using PHP. Currently, I am doing the following:
$pid = shell_exec('ps -ef | grep mosquitto | grep -v grep | awk \'{print $2}\'');
shell_exec('kill -s HUP $pid');
When I run "php test.php" from the command line, I have verified that the signal is sent to the correct process, as expected.
When I invoke the script by visiting http://foo.com/bar/test.php, the signal isn't sent, and shell_exec returns nothing.
For testing, I temporarily ran PHP with root permissions but had the same issue, so I assume this is not a permission issue.
Interestingly, shell_exec returns output for the pwd command and the uptime command to the browser, but not the ls command. But when run from the command line, shell_exec returns output from ls normally.
Is there another limitation of these commands that I'm missing?
Also, a few notes:
Try
echo shell_exec('(ps -ef | grep mosquitto | grep -v grep | awk \'{print $2}\') 2>&1');
and see if any errors are reported. Also, you could try pgrep
, pkill
or killall
instead of messing about with ps
and grep
.
Alternatively, try just running ps
and parsing its full output in PHP yourself. (preg_match()
and/or preg_grep()
may be useful for this.) And you can use posix_kill()
instead of running an external kill
program.
Edit: As per comments, it seems the actual issue was a missing or incorrectly set PATH
environment variable. One way to solve this issue would be to run echo $PATH
in shell, copy the output and set PATH
to the same value in PHP with putenv()
. Another solution is to use which
in shell to determine the full paths to ps
et al., and use those full paths in shell_exec()
.