1import os
2
3from plain.runtime import PLAIN_TEMP_PATH
4
5
6class DevPid:
7 """Manage a pidfile for the running ``plain dev`` command."""
8
9 def __init__(self):
10 self.pidfile = PLAIN_TEMP_PATH / "dev" / "dev.pid"
11
12 def write(self):
13 pid = os.getpid()
14 self.pidfile.parent.mkdir(parents=True, exist_ok=True)
15 with self.pidfile.open("w+") as f:
16 f.write(str(pid))
17
18 def rm(self):
19 if self.pidfile.exists():
20 self.pidfile.unlink()
21
22 def exists(self):
23 if not self.pidfile.exists():
24 return False
25 try:
26 pid = int(self.pidfile.read_text())
27 except (ValueError, OSError):
28 self.rm()
29 return False
30 try:
31 os.kill(pid, 0)
32 except OSError:
33 # Stale pidfile
34 self.rm()
35 return False
36 return True