Linux C/C++ Timer signal handler in userspace

2019-01-28 06:39发布

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.

2条回答
We Are One
2楼-- · 2019-01-28 07:18

A much safer alternative to setitimer (which POSIX 2008 marks OBSolete) 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.

查看更多
smile是对你的礼貌
3楼-- · 2019-01-28 07:38

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.

查看更多
登录 后发表回答