Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a running bash file with php

Tags:

bash

php

I have two buttons "Start Acquisition" and "Stop Acquisition",

The start button executes a bash file and it works fine:

<form action="Control.php" method="post">
<input value="Continous Acquisition " name="Continuous" type="submit">
</form>

<?php
if (isset($_POST['Continous'])) {
shell_exec('sh /Desktop/run_test.sh');
}
?>

I have no idea how to stop the execution when the Stop button is pressed

<form action="Control.php" method="post">

<input value="Stop Acquisition " name="Stop" type="submit">

 </form>

Any help would be appreciated. Thank you.

like image 999
Jack Avatar asked Feb 10 '26 06:02

Jack


1 Answers

To run a program in the background, the command should take this form:

nohup sh /Desktop/run_test.sh &

To stop the program, first find the process id (PID), assuming here that there is only one instance, otherwise you'll need to differentiate the instances:

$exec_output = array();
$actual_pid = 0;
exec("pgrep -fl /Desktop/run_test.sh", $exec_output);
if ($exec_output and preg_match('/^(\d+) .*$/', $exec_output[0], $match)) {
    $actual_pid = $match[1];
}

Then issue a kill command

if ($actual_pid != 0) exec("kill -9 $actual_pid");
like image 129
mike.k Avatar answered Feb 13 '26 10:02

mike.k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!