python / python/cpython

raise_signal docs imply process receives signal not thread

Open
#129,165 0 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Documentation

The documentation of signal.raise_signal(signum) is:

Sends a signal to the calling process

Which somewhat implies the signal is sent to the main thread of the process, ie. equivalent to os.kill(os.getpid(), signum). In actuality the signal is sent to the calling thread, which with the nuance of how Python executes signal handlers can lead to subtly different behaviour with regard to interrupting blocking functions.

The attached example shows how this interpretation can lead to bugs.

$ python example.py kill
Waiting for signal...
Handling signal 15
Wait interrupted by signal
$ python example.py raise_signal
Waiting for signal...

example.py

import os
import signal
import sys
import threading
import time

# Register a handler to flag an event when a signal is received
signalled_flag = threading.Event()


def signal_handler(signum, _frame):
    print(f"Handling signal {signum}")
    signalled_flag.set()


signal.signal(signal.SIGTERM, signal_handler)


# Raise the signal in a separate thread once the main thread is waiting on said event
def do_raise_signal():
    time.sleep(0.01)
    signal.raise_signal(signal.SIGTERM)


def do_kill_process():
    time.sleep(0.01)
    os.kill(os.getpid(), signal.SIGTERM)


match sys.argv:
    case [_, "raise_signal"]:
        thread = threading.Thread(target=do_raise_signal)
    case [_, "kill"]:
        thread = threading.Thread(target=do_kill_process)
    case _:
        print(f"Usage: {sys.argv[0]} [raise_signal|kill]")
        sys.exit(1)


thread.start()

# Wait for the signal to be received
print("Waiting for signal...")
signalled_flag.wait()
print("Wait interrupted by signal")

Linked PRs
  • gh-129167

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the documentation entry for signal.raise_signal(signum) and read the linked signal and threads guidance. Clarify that the signal is sent to the calling thread rather than implying delivery to the process or main thread, then verify the documentation wording and examples remain consistent.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
1/5
Estimated time
Under an hour
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.