Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 444
user623879 Avatar asked Jan 20 '23 03:01

user623879


2 Answers

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.

like image 174
R.. GitHub STOP HELPING ICE Avatar answered Jan 29 '23 00:01

R.. GitHub STOP HELPING ICE


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.

like image 22
ninjalj Avatar answered Jan 28 '23 22:01

ninjalj