I used timer_create()
in the following code. It will trigger the handler only once after 10 seconds.
struct itimerspec itimer = { { 0, 0 }, { 10, 0 } };
struct sigevent si;
memset (&si, 0, sizeof (struct sigevent));
si.sigev_notify = SIGEV_THREAD;
si.sigev_notify_attributes = NULL;
si.sigev_notify_function = t;
if (timer_create (CLOCK_REALTIME, &si, &timer) < 0)
{
fprintf (stderr, "[%d]: %s\n", __LINE__, strerror (errno));
exit (errno);
}
if (timer_settime (timer, 0, &itimer, NULL) < 0)
{
fprintf (stderr, "[%d]: %s\n", __LINE__, strerror (errno));
exit (errno);
}
My question is, after 10 seconds my handler got triggered - now do I have to delete the timer using timer_delete()
before exiting the process? Or, since it is triggered only once, is there no need to delete it explicitly?
Yes, you need to explicitly delete the timer.
Take a look at the man(2) page for timer_create. In the notes section (the third note, specifically), you'll see that every call to timer_create
uses resources in the kernel, and the total number of timers, across all processes, that can be allocated by the kernel at once is limited.
If you don't delete your timers, you will eventually run out of them and any applications that need to allocate timers may fail.
It's just like memory leaks - clean up the resources you use, or you'll eventually run out.
Reply to your follow-up question
In the comments below, you asked if it is okay to call timer_delete
from inside your callback function. I was unsure of how to respond, so I opened question about it myself. The answer seems to be maybe. You can try to experiment with it and see if it works, but I would recommend against it. I've never seen any code that deletes the timer from within the callback, and the idea of deallocating the timer resources before an event has finished being handled makes me nervous.
Also, testing it may yield okay results sometimes, but have random failures since you're dealing with asynchronous events. Furthermore, your main program needs to be running until the callback completes anyway (they run in the same process, just different threads), so you may as well delete the timer in your main thread right before exiting. I think it's the safer solution, and will be easier to debug.