I have an Apache Web server on my RaspberryPi 4 that has a program written in Python on it that will turn on an 8x8 matrix of red led's. I have a HTML and PHP page on the web server so I can remotely execute that script. The HTML is just 2 buttons and on the press of the button it goes to this PHP program:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if ($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['on']))
{
lightOn();
} elseif ($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['off']))
{
lightOff();
}
function lightOn()
{
$command = escapeshellcmd('sudo python3 led_display.py');
$output = shell_exec($command);
header('Location: index.html');
exit;
}
function lightOff()
{
$command = escapeshellcmd('');
$output = shell_exec($command);
header('Location: index.html');
exit;
}
?>
This PHP program just recognizes which of the 2 buttons was pressed and on the press executes a function. For the lightOn() function it is simple as I just execute the script that drives the 8x8 led matrix. However I want the user to be able to stop the script at any time by pressing the other button. On a normal command line interface I would type 'Control + c' to stop any running script. How would I achieve that in PHP through shell_exec, or any other method?
In your server, find out what's the process id (PID) via ps, top or even htop commands. Than you can kill it with the command kill {pid_number}.
Something like:
$ ps aux | grep led_display # the first number that appears is the PID. let's assume it's 1234
$ kill 1234
Assuming that you have control over the sudoers file and know how to make it so your web-server process can execute the command referenced in lightOff without a password you should be able to do
$command = escapeshellcmd('sudo pkill -TERM led_display.py');
Of course that would terminate ANY process called led_display.py, not just the one you started from the web-server process.
EDIT:
What happens if you background the process?
$command = escapeshellcmd('sudo python3 led_display.py > /dev/null 2>&1 &');