terminateProcess function
Future<bool>
terminateProcess(
- int pid, {
- Duration timeout = const Duration(seconds: 10),
- ProcessSignaller sendSignal = Process.killPid,
Sends SIGTERM to pid, waits up to timeout for it to exit, then sends
SIGKILL and waits again. Returns true when the process is gone.
A pid of 0 or less is never signalled (0 is the caller's process group,
-1 every process the user owns) and returns true: there is no process to
stop.
sendSignal defaults to Process.killPid; tests pass a fake so they never
send real signals.
Implementation
Future<bool> terminateProcess(
int pid, {
Duration timeout = const Duration(seconds: 10),
ProcessSignaller sendSignal = Process.killPid,
}) async {
if (pid <= 0) return true;
if (!isProcessAlive(pid)) return true;
for (final signal in [ProcessSignal.sigterm, ProcessSignal.sigkill]) {
try {
sendSignal(pid, signal);
} catch (_) {
return !isProcessAlive(pid);
}
final deadline = DateTime.now().add(timeout);
while (DateTime.now().isBefore(deadline)) {
if (!isProcessAlive(pid)) return true;
await Future<void>.delayed(const Duration(milliseconds: 50));
}
}
return !isProcessAlive(pid);
}