classification
Title: Signal handler is invoked recursively
Type: behavior Stage:
Components: Extension Modules Versions:
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: msakai
Priority: normal Keywords:

Created on 2020-02-24 03:22 by msakai, last changed 2020-02-24 03:22 by msakai.

Messages (1)
msg362562 - (view) Author: Masahiro Sakai (msakai) Date: 2020-02-24 03:22
If I run following program, the parent process fails with "RecursionError: maximum recursion depth exceeded", because the signal handler is invoked during the execution of the same handler.

----
import os
import signal
import time

def f(signum, frame):
    time.sleep(1)

signal.signal(signal.SIGUSR1, f)

parent_pid = os.getpid()
child_pid = os.fork()
if child_pid == 0:
    for i in range(100000):
        os.kill(parent_pid, signal.SIGUSR1)
        time.sleep(0.01)
else:
    os.waitpid(child_pid, 0)
----

This behavior is in contrast to other languages such as C or Ruby.

In C, when a handler function is invoked on a signal, that signal is automatically blocked during the time the handler is running, unless SA_NODEFER is specified.

In Ruby, signal handler is handled in a way similar to Python (i.e. flag is set by C-level signal handler and Ruby/Python-level signal handler is executed later point which is safe for VM), but it prevents recursive signal handler invocation. (Related issue and commit: https://bugs.ruby-lang.org/issues/6009 https://github.com/ruby/ruby/commit/6190bb4d8ad7a07ddb1da8fc687b20612743a34a )

I believe that behavior of C and Ruby is desirable, because writing reentrant signal handler is sometimes error prone.
History
Date User Action Args
2020-02-24 03:22:43msakaicreate