Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why only main thread can set signal handler in Python

Tags:

python

In python's signal handling semantics, only main thread can set signal handler, and only main thread can invoke signal handler.

Why design like this?

like image 304
Jacky1205 Avatar asked Oct 18 '22 12:10

Jacky1205


1 Answers

This comment appears in the cpython sourcefile signalmodule.c:

/* NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS

When threads are supported, we want the following semantics:

  • only the main thread can set a signal handler
  • any thread can get a signal handler
  • signals are only delivered to the main thread

I.e. we don't support "synchronous signals" like SIGFPE (catching
this doesn't make much sense in Python anyway) nor do we support
signals as a means of inter-thread communication, since not all
thread implementations support that (at least our thread library
doesn't).

We still have the problem that in some implementations signals
generated by the keyboard (e.g. SIGINT) are delivered to all
threads (e.g. SGI), while in others (e.g. Solaris) such signals are
delivered to one random thread (an intermediate possibility would
be to deliver it to the main thread -- POSIX?). For now, we have a working implementation that works in all three cases -- the handler ignores signals if getpid() isn't the same as in the main thread.

XXX This is a hack.

*/

My reading of this is that the limitation on setting signal handlers is to simplify the implmentation of signal handling in cpython, by avoiding having to cope with differences in os-level signal implementations.

like image 141
snakecharmerb Avatar answered Oct 25 '22 13:10

snakecharmerb