python / python/cpython

raise_signal docs imply process receives signal not thread

未關閉
#129,165 0 則留言 2 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

docs
主要語言
Python
星號
77.2k
分支
36k
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 摘要。