igneum/tools/fleet/fleet-bg.sh
igneum-labs c8b61dfec1 fleet-bg.sh: the macOS note moved off the case line (a trailing comment swallowed the ;;)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-06 21:43:37 +00:00

16 lines
1.9 KiB
Bash
Executable file

#!/usr/bin/env bash
# Mac-side background jobs by NAME with a pid file, so a job is stopped by its pid and never by a pattern (21:09Z: a
# `pkill -f <log name>` matched nothing, the roll-everything script lived on and wiped a box it had been told to hold).
# tools/fleet/fleet-bg.sh start <name> <command...> runs the command detached, stdout+stderr to ~/Desktop/fleet/<name>.log, pid to ~/Desktop/fleet/pids/<name>.pid
# tools/fleet/fleet-bg.sh stop <name> kills that pid (and its process group) if it is alive, removes the pid file
# tools/fleet/fleet-bg.sh list every job and whether its pid is alive
# macOS has no setsid, so the job runs under nohup alone there (a comment at the end of a case line swallows its ;; : none here).
set -u; P="$HOME/Desktop/fleet/pids"; L="$HOME/Desktop/fleet"; mkdir -p "$P"
case "${1:-}" in
start) n="$2"; shift 2; [ -f "$P/$n.pid" ] && kill -0 "$(cat "$P/$n.pid")" 2>/dev/null && { echo "$n already running (pid $(cat "$P/$n.pid"))"; exit 1; }
if command -v setsid >/dev/null; then nohup setsid "$@" > "$L/$n.log" 2>&1 < /dev/null & else nohup "$@" > "$L/$n.log" 2>&1 < /dev/null & fi; echo $! > "$P/$n.pid"; echo "$n started pid $(cat "$P/$n.pid") log $L/$n.log" ;;
stop) n="$2"; [ -f "$P/$n.pid" ] || { echo "$n: no pid file"; exit 1; }; pid=$(cat "$P/$n.pid")
if kill -0 "$pid" 2>/dev/null; then kill -TERM -- "-$pid" 2>/dev/null || kill -TERM "$pid"; sleep 2; kill -0 "$pid" 2>/dev/null && kill -KILL -- "-$pid" 2>/dev/null; echo "$n stopped (pid $pid)"; else echo "$n not running (pid $pid gone)"; fi; rm -f "$P/$n.pid" ;;
list) for f in "$P"/*.pid; do [ -f "$f" ] || continue; n=$(basename "$f" .pid); pid=$(cat "$f"); kill -0 "$pid" 2>/dev/null && echo "$n pid $pid alive" || echo "$n pid $pid gone"; done ;;
*) echo "usage: fleet-bg.sh start <name> <cmd...> | stop <name> | list"; exit 2 ;;
esac