from pathlib import Path import json,subprocess,time,os,signal,socket,selectors root=Path('/tmp/work');spec=json.loads((root/'launch.json').read_text());p=None unix=socket.socket(socket.AF_UNIX,socket.SOCK_DGRAM);unix.bind(str(root/'inner.sock')) udp=socket.socket(socket.AF_INET,socket.SOCK_DGRAM);udp.bind(('127.0.0.1',0));udp.connect(('127.0.0.1',2001)) sel=selectors.DefaultSelector();sel.register(unix,selectors.EVENT_READ);sel.register(udp,selectors.EVENT_READ) try: with (root/'server-stdout.log').open('w') as log: p=subprocess.Popen(spec['server'],cwd='/tmp/runtime',stdout=log,stderr=subprocess.STDOUT,start_new_session=True) while p.poll() is None and not (root/'stop').exists(): for key,_ in sel.select(.2): if key.fileobj is unix: packet,_=unix.recvfrom(65535);udp.send(packet) else: packet=udp.recv(65535);unix.sendto(packet,str(root/'outer.sock')) finally: if p and p.poll() is None: os.killpg(p.pid,signal.SIGTERM) try:p.wait(timeout=8) except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait(timeout=5) (root/'server-result.json').write_text(json.dumps({'exit':p.returncode if p else None}))