Skip to content

Commit

Permalink
implement parent monitoring thread
Browse files Browse the repository at this point in the history
fixes #7
  • Loading branch information
karmacoma-eth committed Oct 30, 2024
1 parent ca81f8a commit b64c759
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
36 changes: 36 additions & 0 deletions src/jsi/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
import signal
import sys
import threading
import time
from functools import partial

from jsi.config.loader import Config, find_available_solvers, load_definitions
Expand Down Expand Up @@ -134,6 +135,38 @@ def cleanup():
atexit.register(cleanup)


def monitor_parent():
"""
Monitor the parent process and exit if it dies or changes.
Caveats:
- only works on POSIX systems
- only works if called early enough (before the original parent process exits)
"""

parent_pid = os.getppid()

def check_parent():
while True:
try:
current_ppid = os.getppid()

# if parent PID changed (original parent died), we exit
if current_ppid != parent_pid or current_ppid == 1:
stderr.print("parent process died, exiting...")
os.kill(os.getpid(), signal.SIGTERM)
break
time.sleep(1) # check every second
except ProcessLookupError:
# if we can't check parent PID, assume parent died
os.kill(os.getpid(), signal.SIGTERM)
break

# Start monitoring in background thread
monitor_thread = threading.Thread(target=check_parent, daemon=True)
monitor_thread.start()


class BadParameterError(Exception):
pass

Expand Down Expand Up @@ -229,6 +262,9 @@ def main(args: list[str] | None = None) -> int:
global stdout
global stderr

# kick off the parent monitor in the background as early as possible
monitor_parent()

if args is None:
args = sys.argv[1:]

Expand Down
6 changes: 4 additions & 2 deletions src/jsi/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,9 +206,11 @@ def sync_solve(self, file: str) -> str:

listener = ResultListener()
controller = ProcessController(
task, commands, self.config,
task,
commands,
self.config,
start_callback=start_logger,
exit_callback=listener.exit_callback
exit_callback=listener.exit_callback,
)
controller.start()

Expand Down

0 comments on commit b64c759

Please sign in to comment.