One SIGINT while a launch is starting leaves 'ros2 launch' running forever: KeyboardInterrupt is raised inside the event loop and ignored

Aperta
#1,078 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
30/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
python
Ambito
devtools

Direzione di ricerca

The bug sits in launch/launch/launch_service.py, in run_async() and run(), where KeyboardInterrupt is caught and ignored around the asyncio loop. Read AsyncSafeSignalManager to see how SIGINT is delivered through the wake-up socket, then run the reproduction script with a count of 12 to confirm the plain hang. A fix should stop the hang without changing the no-raise behaviour; check it against the launch test suite.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Bug report

Required Info:

  • Operating System:
    • Ubuntu 24.04.5 LTS, Python 3.12.3
  • Installation type:
    • binaries
  • Version or commit hash:
    • ros-jazzy-launch 3.4.12-1noble.20260920.232232, ros-jazzy-ros2launch 0.26.13-1noble.20261006.034901
    • The code in question is the same on rolling today (launch/launch/launch_service.py).
  • DDS implementation:
    • not involved (the launch file starts one plain process, no nodes)
  • Client library (if applicable):
    • N/A
Steps to reproduce issue

Save as issue_repro.py, then source /opt/ros/jazzy/setup.bash && python3 issue_repro.py 12.

It starts a launch of one process that stays until stopped, waits for a line printed by an
OpaqueFunction in the launch description, sends one SIGINT to the launch process only, and
waits up to 10 s for it to exit. It does this two ways:

  • plain: ros2 launch FILE
  • no-raise: the same ros2cli entry point, with signal.signal(signal.SIGINT, lambda *_: None)
    set first, so that Python's default SIGINT handler (the one that raises KeyboardInterrupt in
    the main thread) is not installed.
import os
import shutil
import signal
import subprocess
import sys
import tempfile

READY = "launch description visited"
LAUNCH_FILE = f'''
import signal, sys
from launch import LaunchDescription
from launch.actions import ExecuteProcess, OpaqueFunction


def ready(context):
    print("{READY}", flush=True)


def generate_launch_description():
    return LaunchDescription([
        ExecuteProcess(cmd=[sys.executable, "-c", "import signal; signal.pause()"], name="stays", output="screen"),
        OpaqueFunction(function=ready),
    ])
'''
NO_RAISE = ("import signal, sys; signal.signal(signal.SIGINT, lambda *_: None); "
            "from ros2cli.cli import main; sys.exit(main(argv=['launch', sys.argv[1]]))")

tries = int(sys.argv[1]) if len(sys.argv) > 1 else 12
path = os.path.join(tempfile.mkdtemp(), "one_process.launch.py")
with open(path, "w") as f:
    f.write(LAUNCH_FILE)

for name, command in (("plain", [sys.executable, shutil.which("ros2"), "launch", path]),
                      ("no-raise", [sys.executable, "-c", NO_RAISE, path])):
    hung = 0
    for _ in range(tries):
        p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
                             start_new_session=True)
        for line in p.stdout:  # block until the launch file's own line arrives
            if READY in line:
                break
        os.kill(p.pid, signal.SIGINT)  # one SIGINT, to the launch process only
        try:
            p.communicate(timeout=10)
        except subprocess.TimeoutExpired:
            hung += 1
            os.killpg(p.pid, signal.SIGKILL)
            p.wait()
    print(f"{name:8} did not exit within 10 s of one SIGINT: {hung} of {tries}", flush=True)
Expected behavior

Both ways, the launch reports the interrupt, stops its process and exits.

Actual behavior
plain    did not exit within 10 s of one SIGINT: 12 of 12
no-raise did not exit within 10 s of one SIGINT: 0 of 12

The plain launch stays alive until it is killed. The no-raise launch prints
user interrupted with ctrl-c (SIGINT) and exits 0, so launch's own SIGINT handling
(AsyncSafeSignalManager, through the wake-up socket) works without Python's handler.

Additional information

LaunchService handles SIGINT through AsyncSafeSignalManager, which uses
signal.set_wakeup_fd and does not call signal.signal. Python's default SIGINT handler
therefore stays installed and raises KeyboardInterrupt in the main thread, wherever that thread
is at that moment, which is somewhere inside the asyncio event loop. LaunchService then catches
it and carries on, in two places:

  • run_async(): except KeyboardInterrupt: continue
  • run(): while True: try: return loop.run_until_complete(run_async_task) except KeyboardInterrupt: continue
    ("Note that KeyboardInterrupt is caught and ignored, as signals are handled separately.")

An exception raised at an arbitrary point inside the event loop and then ignored is not safe: it
can interrupt the loop between taking a callback off its ready list and running it, or interrupt
launch's own coroutines mid-step.

The reproduction above stops the launch while it is still starting, where it fails every time
here. I first met this in a larger launch (about ten nodes) that was stopped while its nodes were
already exiting; there it happened in 1 of 14 stops. A stack and state dump of that hung launch
showed: all child processes gone, 28 events in the context's event queue, and the
_process_one_event task still waiting, with the process never exiting. With the non-raising
handler installed before ros2cli's main(), 0 of 70 stops of that launch hung. I have not
dumped the state of the hung launch in the small reproduction, so I cannot say it is the same
internal state, only that the same change removes both.

Workaround used: start the launch through a small wrapper that sets
signal.signal(signal.SIGINT, lambda *_: None) and then calls ros2cli.cli.main(argv=["launch", ...]).

A possible fix in launch: for the duration of run_async(), install a SIGINT handler that does
not raise (and restore the previous one afterwards), instead of catching KeyboardInterrupt
around the event loop. Possibly related older reports: #207, #473.

This report was prepared with the help of an AI assistant; the reproduction was run and its
numbers measured on the machine described above.

Lingua principale
Python
Stelle
156
Fork
200
Merge medio
2g 11h
PR unite (30g)
11

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di ros2/launch

Tutte le issue di ros2/launch

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.