public function stopProcess($pid, $grace = 5)
{
// what are we doing?
$log = usingLog()->startAction("stop process '{$pid}' on host '{$this->args[0]}'");
// is the process running at all?
if (!fromHost($this->args[0])->getPidIsRunning($pid)) {
$log->endAction("process is not running");
return;
}
// yes it is, so stop it
// send a TERM signal to the screen session
$log->addStep("send SIGTERM to process '{$pid}'", function () use($pid) {
if ($this->getIsLocalhost()) {
posix_kill($pid, SIGTERM);
} else {
usingHost($this->args[0])->runCommand("kill {$pid}");
}
});
// has this worked?
$isStopped = $log->addStep("wait for process to terminate", function () use($pid, $grace, $log) {
for ($i = 0; $i < $grace; $i++) {
if (!fromHost($this->args[0])->getPidIsRunning($pid)) {
return true;
}
// process still exists
sleep(1);
}
return false;
});
// did the process stop?
if ($isStopped) {
$log->endAction();
return;
}
$log->addStep("send SIGKILL to process '{$pid}'", function () use($pid) {
if ($this->getIsLocalhost()) {
posix_kill($pid, SIGKILL);
} else {
usingHost($this->args[0])->runCommand("kill -9 {$pid}");
}
sleep(1);
});
// success?
if (fromHost($this->args[0])->getProcessIsRunning($pid)) {
$log->endAction("process is still running :(");
throw new E5xx_ActionFailed(__METHOD__);
}
// all done
$log->endAction("process has finished");
}