Reputation: 753
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.
Upvotes: 3
Views: 797
Reputation: 24549
When you use shell_exec
, it is being run synchronously and waits for the script to complete. Instead, you may want to do something like this instead using proc_open()
and proc_close()
:
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);
$cwd = '/tmp';
$process = proc_open('sh /Desktop/run_test.sh', $descriptorspec, $pipes);
if (is_resource($process))
{
// We have a running process. We can now get the PID
$info = proc_get_status($process);
// Store PID in session to later kill it
$_SESSION['current_pid'] = $info['pid'];
}
Once you have the PID stored in the session (or a file or wherever you want to persist it), you could use system
or exec
to run a kill -9 $pid
command.
References:
http://php.net/manual/en/function.proc-open.php http://php.net/manual/en/function.proc-get-status.php
Upvotes: 2
Reputation: 3427
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");
Upvotes: 2