user623879
user623879

Reputation: 4142

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.

Upvotes: 4

Views: 6130

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

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.

Upvotes: 6

ninjalj
ninjalj

Reputation: 43688

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.

Upvotes: 3

Related Questions