killTree static method
Stops a worker and everything it started (flutter, Gradle, xcodebuild), children first so none are orphaned.
Implementation
static void killTree(int rootPid, {bool includeRoot = true}) {
try {
if (Platform.isWindows) {
Process.runSync('taskkill', ['/PID', '$rootPid', '/T', '/F']);
return;
}
final ps = Process.runSync('ps', ['-A', '-o', 'pid=,ppid=']);
final children = <int, List<int>>{};
for (final line in ps.stdout.toString().split('\n')) {
final parts = line.trim().split(RegExp(r'\s+'));
if (parts.length != 2) continue;
final pid = int.tryParse(parts[0]);
final ppid = int.tryParse(parts[1]);
if (pid == null || ppid == null) continue;
children.putIfAbsent(ppid, () => []).add(pid);
}
final order = <int>[];
void visit(int pid) {
for (final child in children[pid] ?? const <int>[]) {
visit(child);
}
order.add(pid);
}
visit(rootPid);
if (!includeRoot) order.remove(rootPid);
for (final pid in order) {
Process.killPid(pid, ProcessSignal.sigterm);
}
} catch (_) {
Process.killPid(rootPid);
}
}