From a2e3647e8e6242aec763050670deebf5bb0438cc Mon Sep 17 00:00:00 2001 From: TEJA P C Date: Thu, 19 Nov 2026 18:10:25 -0600 Subject: [PATCH 1/3] Restore foreground process group when the debuggee exits --- src/debugpy/launcher/debuggee.py | 27 +++++++ tests/tests/test_launcher_debuggee.py | 112 ++++++++++++++++++++++++++ 2 files changed, 139 insertions(+) create mode 100644 tests/tests/test_launcher_debuggee.py diff --git a/src/debugpy/launcher/debuggee.py b/src/debugpy/launcher/debuggee.py index 0b70e1eaa..55b62d3f4 100644 --- a/src/debugpy/launcher/debuggee.py +++ b/src/debugpy/launcher/debuggee.py @@ -196,6 +196,30 @@ def kill(): log.swallow_exception("Failed to kill {0}", describe()) +def _restore_foreground_process_group(): + if process is None: + return + + try: + # signal.signal() only works in the main thread, and this can run in the + # wait_for_exit thread, so SIGTTOU is blocked in the calling thread instead. + old_mask = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTTOU}) + try: + tty = os.open("/dev/tty", os.O_RDWR) + try: + if os.tcgetpgrp(tty) == process.pid: + os.tcsetpgrp(tty, os.getpgrp()) + finally: + os.close(tty) + finally: + signal.pthread_sigmask(signal.SIG_SETMASK, old_mask) + except Exception: + # Not an error - /dev/tty doesn't work when there's no terminal. + log.swallow_exception( + "Failed to restore foreground process group", level="info" + ) + + def wait_for_exit(): try: # wait_for_exit() only runs after the debuggee was spawned successfully, so @@ -213,6 +237,9 @@ def wait_for_exit(): log.swallow_exception("Couldn't determine process exit code") code = -1 + if sys.platform != "win32": + _restore_foreground_process_group() + log.info("{0} exited with code {1}", describe(), code) output.wait_for_remaining_output() diff --git a/tests/tests/test_launcher_debuggee.py b/tests/tests/test_launcher_debuggee.py new file mode 100644 index 000000000..ca9090758 --- /dev/null +++ b/tests/tests/test_launcher_debuggee.py @@ -0,0 +1,112 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See LICENSE in the project root +# for license information. + +import os +import subprocess +import sys +import textwrap +import time + +import pytest + +DRIVER = textwrap.dedent(""" + import os + import sys + import time + + from debugpy import launcher + from debugpy.launcher import debuggee + + + class Channel: + def __init__(self): + self.events = [] + + def send_event(self, name, body=None): + self.events.append(name) + + + launcher.channel = Channel() + debuggee.spawn( + "debuggee", [sys.executable, "-c", "pass"], dict(os.environ), False + ) + + deadline = time.time() + 60 + while "terminated" not in launcher.channel.events: + if time.time() > deadline: + print("Timed out waiting for the debuggee to exit.", flush=True) + sys.exit(2) + time.sleep(0.05) + + foreground = os.tcgetpgrp(0) + print( + "Foreground process group is {0}, launcher process group is {1}.".format( + foreground, os.getpgrp() + ), + flush=True, + ) + sys.exit(0 if foreground == os.getpgrp() else 1) + """) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="POSIX foreground process groups only" +) +def test_launcher_restores_foreground_process_group(tmp_path): + import fcntl + import pty + import select + import termios + + driver = tmp_path / "driver.py" + driver.write_text(DRIVER) + + src = os.path.join(os.path.dirname(__file__), "..", "..", "src") + env = dict(os.environ) + env["PYTHONPATH"] = os.path.abspath(src) + os.pathsep + env.get("PYTHONPATH", "") + + master, slave = pty.openpty() + + def preexec_fn(): + os.setsid() + fcntl.ioctl(0, termios.TIOCSCTTY, 0) + + proc = subprocess.Popen( + [sys.executable, str(driver)], + stdin=slave, + stdout=slave, + stderr=slave, + preexec_fn=preexec_fn, + env=env, + close_fds=True, + ) + os.close(slave) + + output = b"" + timed_out = False + try: + deadline = time.time() + 90 + while proc.poll() is None: + if time.time() > deadline: + timed_out = True + break + ready, _, _ = select.select([master], [], [], 0.1) + if master in ready: + try: + chunk = os.read(master, 65536) + except OSError: + break + if not chunk: + break + output += chunk + finally: + os.close(master) + if proc.poll() is None: + proc.kill() + + proc.wait(timeout=10) + assert ( + not timed_out + ), "Driver did not exit in time; output so far:\n" + output.decode(errors="replace") + assert proc.returncode == 0, output.decode(errors="replace") From 699c636af5d3991706e2fe53fa82b7aa97feb0d4 Mon Sep 17 00:00:00 2001 From: TEJA P C Date: Thu, 19 Nov 2026 19:05:47 -0600 Subject: [PATCH 2/3] Restore the foreground group after captured output drains --- src/debugpy/launcher/debuggee.py | 6 +-- tests/tests/test_launcher_debuggee.py | 68 ++++++++++++++++++++++++--- 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/src/debugpy/launcher/debuggee.py b/src/debugpy/launcher/debuggee.py index 55b62d3f4..141aacfae 100644 --- a/src/debugpy/launcher/debuggee.py +++ b/src/debugpy/launcher/debuggee.py @@ -237,12 +237,12 @@ def wait_for_exit(): log.swallow_exception("Couldn't determine process exit code") code = -1 - if sys.platform != "win32": - _restore_foreground_process_group() - log.info("{0} exited with code {1}", describe(), code) output.wait_for_remaining_output() + if sys.platform != "win32": + _restore_foreground_process_group() + # Determine whether we should wait or not before sending "exited", so that any # follow-up "terminate" requests don't affect the predicates. should_wait = any(pred(code) for pred in wait_on_exit_predicates) diff --git a/tests/tests/test_launcher_debuggee.py b/tests/tests/test_launcher_debuggee.py index ca9090758..8a9ffd3db 100644 --- a/tests/tests/test_launcher_debuggee.py +++ b/tests/tests/test_launcher_debuggee.py @@ -2,7 +2,9 @@ # Licensed under the MIT License. See LICENSE in the project root # for license information. +import json import os +import re import subprocess import sys import textwrap @@ -11,6 +13,7 @@ import pytest DRIVER = textwrap.dedent(""" + import json import os import sys import time @@ -29,7 +32,10 @@ def send_event(self, name, body=None): launcher.channel = Channel() debuggee.spawn( - "debuggee", [sys.executable, "-c", "pass"], dict(os.environ), False + "debuggee", + json.loads(os.environ["DEBUGGEE_ARGV"]), + dict(os.environ), + os.environ["DEBUGGEE_REDIRECT_OUTPUT"] == "1", ) deadline = time.time() + 60 @@ -49,11 +55,32 @@ def send_event(self, name, body=None): sys.exit(0 if foreground == os.getpgrp() else 1) """) +DEBUGGEE_WITH_CHILD = textwrap.dedent(""" + import subprocess + import sys -@pytest.mark.skipif( - sys.platform == "win32", reason="POSIX foreground process groups only" -) -def test_launcher_restores_foreground_process_group(tmp_path): + CHILD = ''' + import os + import time + + deadline = time.time() + 5 + while time.time() < deadline: + if os.tcgetpgrp(0) != os.getpgrp(): + break + time.sleep(0.05) + print( + "Child foreground is {0}, child group is {1}.".format( + os.tcgetpgrp(0), os.getpgrp() + ), + flush=True, + ) + ''' + + subprocess.Popen([sys.executable, "-c", CHILD]) + """) + + +def run_driver(tmp_path, argv, redirect_output): import fcntl import pty import select @@ -65,6 +92,8 @@ def test_launcher_restores_foreground_process_group(tmp_path): src = os.path.join(os.path.dirname(__file__), "..", "..", "src") env = dict(os.environ) env["PYTHONPATH"] = os.path.abspath(src) + os.pathsep + env.get("PYTHONPATH", "") + env["DEBUGGEE_ARGV"] = json.dumps(argv) + env["DEBUGGEE_REDIRECT_OUTPUT"] = "1" if redirect_output else "0" master, slave = pty.openpty() @@ -109,4 +138,31 @@ def preexec_fn(): assert ( not timed_out ), "Driver did not exit in time; output so far:\n" + output.decode(errors="replace") - assert proc.returncode == 0, output.decode(errors="replace") + return proc.returncode, output + + +@pytest.mark.skipif( + sys.platform == "win32", reason="POSIX foreground process groups only" +) +def test_launcher_restores_foreground_process_group(tmp_path): + returncode, output = run_driver( + tmp_path, [sys.executable, "-c", "pass"], redirect_output=False + ) + assert returncode == 0, output.decode(errors="replace") + + +@pytest.mark.skipif( + sys.platform == "win32", reason="POSIX foreground process groups only" +) +def test_launcher_restores_foreground_after_surviving_child(tmp_path): + program = tmp_path / "debuggee.py" + program.write_text(DEBUGGEE_WITH_CHILD) + + returncode, output = run_driver( + tmp_path, [sys.executable, str(program)], redirect_output=True + ) + assert returncode == 0, output.decode(errors="replace") + + match = re.search(rb"Child foreground is (\d+), child group is (\d+)\.", output) + assert match is not None, output.decode(errors="replace") + assert match.group(1) == match.group(2), output.decode(errors="replace") From 3f43a9f5950d72a57306a104729828fb1019f86d Mon Sep 17 00:00:00 2001 From: TEJA P C Date: Tue, 24 Nov 2026 02:44:11 +0000 Subject: [PATCH 3/3] Move the win32 guard into _restore_foreground_process_group --- src/debugpy/launcher/debuggee.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/debugpy/launcher/debuggee.py b/src/debugpy/launcher/debuggee.py index 141aacfae..be0a955a4 100644 --- a/src/debugpy/launcher/debuggee.py +++ b/src/debugpy/launcher/debuggee.py @@ -197,6 +197,9 @@ def kill(): def _restore_foreground_process_group(): + if sys.platform == "win32": + return + if process is None: return @@ -240,8 +243,7 @@ def wait_for_exit(): log.info("{0} exited with code {1}", describe(), code) output.wait_for_remaining_output() - if sys.platform != "win32": - _restore_foreground_process_group() + _restore_foreground_process_group() # Determine whether we should wait or not before sending "exited", so that any # follow-up "terminate" requests don't affect the predicates.