Linux C/C++ Timer signal handler in userspace
I need a function(eg signal handler) in C/C++ linux that gets activated every 'n' milliseconds. How do I setup signals etc...to register to timer events at the millisecond resolution.
Accuracy is not super critical, but need within hundred ms or so.
I am ne开发者_JAVA百科w to linux and I really don't know where to start.
A much safer alternative to setitimer
(which POSIX 2008 marks OBS
olete) would be to use POSIX timers, and have the timer expiration function run in a thread rather than a signal handler. This way you are not restricted to only using async-signal-safe functions. They're documented here:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_08_05
If you don't like the POSIX timers API, you could instead create a thread that merely sleeps in a loop, and block the timer signal in all threads except that thread. Then you will be free to use whatever functions you like in the signal handler, since it will run in a separate thread and there is no danger of it interrupting an async-signal-unsafe function.
setitimer(2)
is a good start, but do you really want to go asynchronous with signals? Otherwise, you could have a main loop with select(2)
or poll(2)
and an appropiate timeout.
精彩评论