skrrgwasme skrrgwasme - 25 days ago 9
C Question

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

The Question



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

Are there any hidden implications or undesirable side-effects to calling
timer_delete
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.

Background



Another SO user asked this question, which essentially says, "do I really need to delete my timers after calling
timer_create
? 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

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.

Comments