"""Spawn run_server.py detached with valid file handles (Windows-safe). The child gets stdout/stderr = log file and stdin = NUL. This avoids: - OSError(9)/'lost sys.stderr' from broken inherited console handles - parent hangs when the child keeps an inherited stdout pipe open Usage: start_server.py [logfile] [pidfile] """ from __future__ import annotations import subprocess import sys import traceback from pathlib import Path def main() -> int: if len(sys.argv) not in (2, 3, 4): print("usage: start_server.py [logfile] [pidfile]", file=sys.stderr) return 2 port = sys.argv[1] root = Path(__file__).resolve().parents[1] log_path = Path(sys.argv[2]) if len(sys.argv) >= 3 else root / "data" / "logs" / "wvt.log" pid_path = Path(sys.argv[3]) if len(sys.argv) >= 4 else root / "data" / "wvt.pid" log_path.parent.mkdir(parents=True, exist_ok=True) python_exe = sys.executable child = Path(__file__).resolve().parent / "run_server.py" cmd = [python_exe, str(child), port, str(log_path), str(pid_path)] flags = 0 if hasattr(subprocess, "DETACHED_PROCESS"): flags |= subprocess.DETACHED_PROCESS flags |= subprocess.CREATE_NEW_PROCESS_GROUP # Two separate unbuffered handles: child writes server output to wvt.log. out_f = open(log_path, "ab", buffering=0) err_f = open(log_path, "ab", buffering=0) proc = subprocess.Popen( cmd, cwd=str(root), stdin=subprocess.DEVNULL, stdout=out_f, stderr=err_f, creationflags=flags, close_fds=True, ) out_f.close() err_f.close() pid_path.parent.mkdir(parents=True, exist_ok=True) pid_path.write_text(str(proc.pid) + "\n", encoding="utf-8") print(f"spawned pid={proc.pid} port={port} log={log_path}") return 0 if __name__ == "__main__": try: raise SystemExit(main()) except SystemExit: raise except Exception: root = Path(__file__).resolve().parents[1] try: crash = root / "data" / "logs" / "wvt-crash.log" crash.parent.mkdir(parents=True, exist_ok=True) crash.write_text(traceback.format_exc(), encoding="utf-8") except Exception: pass raise