backstory/src/kill-server.sh
2025-04-29 15:53:04 -07:00

58 lines
1.5 KiB
Bash
Executable File

#!/bin/bash
# Ensure input was provided
if [[ -z "$1" ]]; then
TARGET=$(readlink -f "src/server.py")
else
TARGET=$(readlink -f "$1")
fi
# Resolve user-supplied path to absolute path
if [[ ! -f "$TARGET" ]]; then
echo "Target file '$TARGET' not found."
exit 1
fi
# Loop through python processes and resolve each script path
PID=""
for pid in $(pgrep -f python); do
if [[ -r "/proc/$pid/cmdline" ]]; then
# Get the full command line, null-separated
cmdline=$(tr '\0' ' ' < "/proc/$pid/cmdline")
# Extract the script argument (naively assumes it's the first non-option)
script_arg=$(echo "$cmdline" | awk '{for (i=2;i<=NF;i++) if ($i !~ /^-/) {print $i; exit}}')
# Try resolving the script path relative to the process's cwd
script_path=$(readlink -f "/proc/$pid/cwd/$script_arg" 2>/dev/null)
if [[ "$script_path" == "$TARGET" ]]; then
PID=$pid
break
fi
fi
done
if [[ -z "$PID" ]]; then
echo "No Python process found running '$TARGET'."
exit 1
fi
echo "Found process $PID running $TARGET"
# Get times
file_time=$(stat -c %Y "$TARGET")
proc_time=$(stat -c %Y "/proc/$PID")
# if (( file_time > proc_time )); then
# echo "Script '$TARGET' is newer than process $PID. Killing $PID"
kill -9 "$PID"
if [[ $? -ne 0 ]]; then
echo "Failed to kill process $PID."
exit 1
fi
echo "Process $PID killed."
# else
# echo "Script '$TARGET' is older than or same age as process $PID."
# fi