I am running a shell script file through PHP. When the user click Run button it start executing the commands using the following lines:
if( isset($_POST["runBtn"]) ){
$command = file_get_contents('runScript.sh');
exec("bash -c $command 2>&1 & echo $!", $output, $return_var);
$pid = (int)$output[0];
$_SESSION["PID"] = $pid;
}
These above lines run the script perfect and give me the PID after finishing the process.
However, in the same page I have a cancel button that when user click it, it should stop the exec function execution immediately and kill the bash commands that is running in background.
Here the cancel button:
<button type="button" name="cancelBtn" onclick="button1()"> Cancel Experiment</button>
Here what I am trying to do:
function button1()
{
console.log("I am the cancel button"); //this just for debugging
$.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {functionname: 'cancelEx'},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
console.log("I am the cancel success");
console.log(obj.result);
}else {
console.log(obj.error);
}
}
});
}
Here is myFunction.php:
<?php
header('Content-Type: application/json');
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'cancelEx':
echo "<script> console.log('Test here pid from cnacel button')</script>";
$command = "ps ax | awk '! /awk/ && /runScript.sh/ { print $1}'";
$pid = shell_exec($command);
echo "<script> console.log('Test here pid from cnacel button')</script>";
echo "<script> console.log(".$pid.")</script>";
shell_exec("kill -9 $pid");
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
echo json_encode($aResult);
?>
The problem is that ajax call not working until the exec function and the bash commands finish execution.
How could I make cancel button take effect while the process still running? How could cancel button stop the exec function of runBtn
and kill the runScript.sh
?