Can signal.alarm be safely cleared in python?

Chris Angelico rosuav at gmail.com
Fri Nov 18 04:03:31 EST 2016


On Fri, Nov 18, 2016 at 7:51 PM, dieter <dieter at handshake.de> wrote:
> Pedro Franco de Carvalho <reddopp at gmail.com> writes:
>
>> Assume a python program sets a handler function for the
>> `signal.SIGALRM` signal, and then schedules an alarm in T seconds with
>> `signal.alarm(T)`.
>>
>> Assume the program later cancels any scheduled alarm with `signal.alarm(0)`.
>
> I do not think so. You might have a "race condition".
>
> I think of the following (hypothetical) situation: the alarm
> arrives while "signal.alarm(0)" processing has started but not yet finished.
> In this case, the alarm arrival will schedule the alarm handler
> activation - but, as "signal.alarm" is "C" implemented, the handler
> will not be activated immediately (but delayed until the next
> execution of Python code).

That situation would be safe if the cancelling of the timer is in a
sense of "okay, don't bother" rather than "this must now not happen".
For example, you could set a timeout on some operation (say, a
subprocess execution) by setting an alarm. When the process
terminates, you cancel the alarm. If, just after you cancel the alarm,
the signal comes through, that's fine - the handler will already need
to cope with the process having just finished.

So I would say that it's safe IFF you accept this restriction.

ChrisA



More information about the Python-list mailing list