简体   繁体   中英

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 new 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM