robust clean-up with SIGTERM (was Re: Again, how to write a cleanup function for a module in C )

Donn Cave donn at drizzle.com
Sat Aug 16 00:01:44 EDT 2003


Quoth "Changjune Kim" <juneaftn at REMOVETHIShanmail.net>:
[ ... re why signal handling may not be 100% reliable ]

| When signals are generated successively in a very short time, python
| interpreter might screw up some of them. Basically, the interpreter checks
| every checkinterval(default 100) if it has pending signal handler calls,
| and process them. When a signal is generated, it registers the signal and
| put its handler on the pending calls. As you can see there are potential
| race conditions.
|
| Check signalmodule.c and ceval.c.
|
| I don't have a good idea on making signal handling always safe &
| guaranteed. Maybe someone else can help?

Well, there are ways to defer signal delivery while you process
the signals that have already been delivered -

   /* (untested) */
   sigset_t mask, prev_mask;
   sigfillset(&mask);
   sigprocmask(SIG_SETMASK, &mask, &prev_mask);
   /*  All signals now blocked. */
   ... process state from signal deliveries
   sigprocmask(SIG_SETMASK, &prev_mask, 0);

and you can set a signal handler up such that signals are blocked
while it executes -

   sa.sa_handler = signal_handler;
   sa.sa_flags = 0;
   sigfillset(&sa.sa_mask);
   sigaction(SIGTERM, &sa, 0);

This assumes signal handling per POSIX 1003.1, which may be part
of the reason if Python isn't trying to do it.  Then there are
some naturally intrinsic problems with signal handling in Python
that make delivery unreliable in a different way - your signal
handler may be invoked much later than the signal is delivered.
(And of course if you're using threads, there are more problems.)
That's only relevant to the present question because, given the
unavoidable weaknesses in Python signal handling, it may not be
worth even a slight headache from platforms that don't support
POSIX signal handling or don't support it correctly.

	Donn Cave, donn at drizzle.com




More information about the Python-list mailing list