skrrgwasme skrrgwasme - 10 months ago 60
C Question

Is it okay to delete a POSIX timer in the event handler function?

The Question

If I call
with the
constant stored in the
field in my
structure, then when the timer event happens, my
callback will be called.

Are there any hidden implications or undesirable side-effects to calling
from within my callback function?

Specific Concerns

My initial thought was that it should be fine. However, I don't fully understand the mechanics that are operating behind the scenes, and I'm concerned about there being proper cleanup of the callback's thread and handling of the signals if the timer and it's associated structures are removed before handling is complete.


Another SO user asked this question, which essentially says, "do I really need to delete my timers after calling
? My answer was a resounding yes. He then asked a follow-up question in the comments: "is it okay to do that from the timer callback function?" and I didn't have a good answer to that.

Answer Source

It looks that in principle it is not allowed to call timer_create or timer_delete, at least on Linux. signal(7) is only allowing async-signal-safe functions to be called directly or indirectly from a signal handler, and strangely timer_create and timer_delete is not listed amongst them (perhaps it is a typo and they both should be listed as async-signal-safe, since both timer_create(2) & timer_delete(2) are in section 2 of the man pages, and appear in syscalls(2))

Notice that POSIX signal concepts page does not list timer_create as possible in a signal handler. I imagine that on some operating systems these timer functions might be implemented entirely in the C library (not in the kernel).

My guess (since timer_create and timer_delete is a syscall on Linux listed in <asm/unistd.h>) is that timer_create and timer_delete are in fact async-signal-safe so can be called from a Linux signal handler. This might be false on other POSIX implementations.