94 lines
3.1 KiB
Python
94 lines
3.1 KiB
Python
"""The shells a running claude has started, read from /proc (Linux), and how to stop one."""
|
|
import dataclasses
|
|
import os
|
|
import signal
|
|
import stat
|
|
|
|
# The command names of a shell claude starts for a Bash call.
|
|
SHELL_NAMES = frozenset({"bash", "dash", "sh", "zsh"})
|
|
# How much of a shell's command line a Shell keeps.
|
|
COMMAND_CHARS = 200
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Shell:
|
|
pid: int
|
|
# Epoch seconds at which the shell started.
|
|
started: float
|
|
command: str
|
|
# Epoch seconds of the last write to the file the shell's output goes to; its start where the output goes to no file.
|
|
written: float
|
|
# Whether the shell or one of its descendants is run-heavy, which holds a slot of the machine's heavy work or waits for one.
|
|
holds_slot: bool
|
|
|
|
|
|
def parent_and_start(pid: int) -> tuple[int, int, str] | None:
|
|
"""The parent pid, the start time in clock ticks since boot and the command name of a process; None where it is gone."""
|
|
try:
|
|
with open(f"/proc/{pid}/stat") as handle:
|
|
text = handle.read()
|
|
except OSError:
|
|
return None
|
|
# The name sits in parentheses and may hold spaces or parentheses itself, so split at the last one.
|
|
name = text[text.index("(") + 1 : text.rindex(")")]
|
|
fields = text[text.rindex(")") + 2 :].split()
|
|
return int(fields[1]), int(fields[19]), name
|
|
|
|
|
|
def children_of(pid: int) -> list[int]:
|
|
return [int(entry) for entry in os.listdir("/proc") if entry.isdigit() and (found := parent_and_start(int(entry))) and found[0] == pid]
|
|
|
|
|
|
def command_of(pid: int) -> str:
|
|
try:
|
|
with open(f"/proc/{pid}/cmdline", "rb") as handle:
|
|
return handle.read().replace(b"\0", b" ").decode(errors="replace").strip()
|
|
except OSError:
|
|
return ""
|
|
|
|
|
|
def descendants(pid: int) -> list[int]:
|
|
"""Every process below pid, nearest first."""
|
|
found = children_of(pid)
|
|
for child in list(found):
|
|
found += descendants(child)
|
|
return found
|
|
|
|
|
|
def boot_time() -> float:
|
|
with open("/proc/stat") as handle:
|
|
return next(float(line.split()[1]) for line in handle if line.startswith("btime"))
|
|
|
|
|
|
def output_written(pid: int, started: float) -> float:
|
|
"""When the file that pid's standard output goes to was last written; started where that is a pipe or a terminal, whose writes leave no time."""
|
|
try:
|
|
info = os.stat(f"/proc/{pid}/fd/1")
|
|
except OSError:
|
|
return started
|
|
return info.st_mtime if stat.S_ISREG(info.st_mode) else started
|
|
|
|
|
|
def shells_of(claude_pid: int) -> list[Shell]:
|
|
"""The shells that are children of claude_pid."""
|
|
booted = boot_time()
|
|
ticks = os.sysconf("SC_CLK_TCK")
|
|
shells = []
|
|
for pid in children_of(claude_pid):
|
|
found = parent_and_start(pid)
|
|
if found is None or found[2] not in SHELL_NAMES:
|
|
continue
|
|
started = booted + found[1] / ticks
|
|
below = [pid, *descendants(pid)]
|
|
shells.append(Shell(pid, started, command_of(pid)[:COMMAND_CHARS], output_written(pid, started), any("run-heavy" in command_of(each) for each in below)))
|
|
return shells
|
|
|
|
|
|
def stop(shell: Shell) -> None:
|
|
"""Ends the shell and everything below it, so the loop it ran doesn't outlive it."""
|
|
for pid in [*reversed(descendants(shell.pid)), shell.pid]:
|
|
try:
|
|
os.kill(pid, signal.SIGTERM)
|
|
except OSError:
|
|
pass
|