I have an Apache Web server on my RaspberryPi 4 that has a program written in Python on it that will turn on an 8×8 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 8×8 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?
2
Answers
In your server, find out what’s the process id (PID) via
ps
,top
or evenhtop
commands. Than you can kill it with the commandkill {pid_number}
.Something like:
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 inlightOff
without a password you should be able to doOf 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?