import ctypes
import os
import signal
import subprocess
import sys
import time

libc = ctypes.CDLL(None, use_errno=True)
if libc.prctl(36, 1, 0, 0, 0) != 0:
    raise OSError(ctypes.get_errno(), 'PR_SET_CHILD_SUBREAPER')
primary = subprocess.Popen(sys.argv[1:])
print(f'SUPERVISOR tracked driver PID {primary.pid}', flush=True)
status = primary.wait()
deadline = time.monotonic() + 10
signalled = set()
while True:
    try:
        while os.waitpid(-1, os.WNOHANG)[0]:
            pass
    except ChildProcessError:
        break
    children = open(f'/proc/{os.getpid()}/task/{os.getpid()}/children').read().split()
    for text in children:
        pid = int(text)
        if pid not in signalled:
            print(f'SUPERVISOR stopping adopted tracked descendant PID {pid}', flush=True)
            try:
                os.kill(pid, signal.SIGTERM)
            except ProcessLookupError:
                pass
            signalled.add(pid)
        if time.monotonic() > deadline:
            try:
                os.kill(pid, signal.SIGKILL)
            except ProcessLookupError:
                pass
    time.sleep(0.05)
print('SUPERVISOR all started descendants reaped', flush=True)
sys.exit(status)
