python / python/cpython

raise_signal docs imply process receives signal not thread

未关闭
#129,165 0 条评论 2 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

docs
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 signal.raise_signal(signum) 的文档条目开始,阅读链接的信号和线程指南。明确说明信号会发送到调用线程,而不是暗示信号会发送到进程或主线程,然后验证文档措辞和示例仍然保持一致。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
documentation
Issue 类型
文档
难度
1/5
预计耗时
1 小时以内
活跃度
停滞
描述清晰度
描述清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。