# Buggy code
def inject(pid, debugpy_args):
    host, port = Connection.listener.getsockname()

    cmdline = [
        sys.executable,
        compat.filename(os.path.dirname(debugpy.__file__)),
        "--client",
        "--host",
        host,
        "--port",
        str(port),
    ]
    if adapter.access_token is not None:
        cmdline += ["--client-access-token", adapter.access_token]
    cmdline += debugpy_args
    cmdline += ["--pid", str(pid)]

    log.info("Spawning attach-to-PID debugger injector: {0!r}", cmdline)
    try:
        injector = subprocess.Popen(
            cmdline,
            bufsize=0,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
        )
    except Exception as exc:
        log.exception("Failed to inject debug server into process with PID={0}", pid)
        raise messaging.MessageHandlingError(
            fmt(
                "Failed to inject debug server into process with PID={0}: {1}", pid, exc
            )
        )

    # We need to capture the output of the injector - otherwise it can get blocked
    # on a write() syscall when it tries to print something.

    def capture_output():
        while True:
            line = injector.stdout.readline()
            if not line:
                break
            log.info("Injector[PID={0}] output:\n{1}", pid, line.rstrip())
        log.info("Injector[PID={0}] exited.", pid)

    thread = threading.Thread(
        target=capture_output, name=fmt("Injector[PID={0}] output", pid)
    )
    thread.daemon = True
    thread.start()


# Traceback (ConnectionRefusedError)
C:\Python37\python.exe c:\Users\kanadig\.vscode\extensions\ms-python.python-2020.2.60897-dev\pythonFiles\lib\python\new_ptvsd\wheels\ptvsd\launcher C:\GIT\issues\issue9214/test_mp.py
Could not connect to 127.0.0.1: 50734
Traceback (most recent call last):
File "c:\Users\kanadig\.vscode\extensions\ms-python.python-2020.2.60897-dev\pythonFiles\lib\python\new_ptvsd\wheels\ptvsd\_vendored\pydevd\_pydevd_bundle\pydevd_comm.py", line 514, in start_client
s.connect((host, port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "c:\Users\kanadig\.vscode\extensions\ms-python.python-2020.2.60897-dev\pythonFiles\lib\python\new_ptvsd\wheels\ptvsd\_vendored\pydevd\pydevd.py", line 2550, in settrace
client_access_token,
File "c:\Users\kanadig\.vscode\extensions\ms-python.python-2020.2.60897-dev\pythonFiles\lib\python\new_ptvsd\wheels\ptvsd\_vendored\pydevd\pydevd.py", line 2610, in _locked_settrace
py_db.connect(host, port)  # Note: connect can raise error.
File "c:\Users\kanadig\.vscode\extensions\ms-python.python-2020.2.60897-dev\pythonFiles\lib\python\new_ptvsd\wheels\ptvsd\_vendored\pydevd\pydevd.py", line 1179, in connect
s = start_client(host, port)
File "c:\Users\kanadig\.vscode\extensions\ms-python.python-2020.2.60897-dev\pythonFiles\lib\python\new_ptvsd\wheels\ptvsd\_vendored\pydevd\_pydevd_bundle\pydevd_comm.py", line 514, in start_client
s.connect((host, port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "C:\Python37\lib\concurrent\futures\process.py", line 102, in _python_exit
thread_wakeup.wakeup()
File "C:\Python37\lib\concurrent\futures\process.py", line 90, in wakeup
self._writer.send_bytes(b"")
File "C:\Python37\lib\multiprocessing\connection.py", line 183, in send_bytes
self._check_closed()
File "C:\Python37\lib\multiprocessing\connection.py", line 136, in _check_closed
raise OSError("handle is closed")
OSError: handle is closed

# Fixed code
def inject(pid, debugpy_args):
    host, port = listener.getsockname()

    cmdline = [
        sys.executable,
        compat.filename(os.path.dirname(debugpy.__file__)),
        "--client",
        "--host",
        host,
        "--port",
        str(port),
    ]
    if adapter.access_token is not None:
        cmdline += ["--client-access-token", adapter.access_token]
    cmdline += debugpy_args
    cmdline += ["--pid", str(pid)]

    log.info("Spawning attach-to-PID debugger injector: {0!r}", cmdline)
    try:
        injector = subprocess.Popen(
            cmdline,
            bufsize=0,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
        )
    except Exception as exc:
        log.exception("Failed to inject debug server into process with PID={0}", pid)
        raise messaging.MessageHandlingError(
            fmt(
                "Failed to inject debug server into process with PID={0}: {1}", pid, exc
            )
        )

    # We need to capture the output of the injector - otherwise it can get blocked
    # on a write() syscall when it tries to print something.

    def capture_output():
        while True:
            line = injector.stdout.readline()
            if not line:
                break
            log.info("Injector[PID={0}] output:\n{1}", pid, line.rstrip())
        log.info("Injector[PID={0}] exited.", pid)

    thread = threading.Thread(
        target=capture_output, name=fmt("Injector[PID={0}] output", pid)
    )
    thread.daemon = True
    thread.start()