4

I have a small program that needs to be run in a small Linux embedded system (ARM). It is written in C. It needs to poll some data (2x64-bit) from an API provided by the system manufacturer, and then do some calculations and send the data through the network. The data should be polled around 30 times every second (30Hz).

What would be the best way to do it in C? I've seen solutions using sleep(), but it does not seem to be the best option for the job.

unwind
  • 391,730
  • 64
  • 469
  • 606
fazineroso
  • 7,196
  • 7
  • 31
  • 42
  • 2
    [Timers](http://linux.die.net/man/2/timer_create)? [`nanosleep`](http://linux.die.net/man/2/nanosleep)? – Some programmer dude Oct 07 '13 at 14:41
  • Could you elaborate on the answer? What would be the advantage on using either of them? I am looking to have this process running 'forever' (uptime > 30 days) on the machine, and I want to free the CPU as much as possible. – fazineroso Oct 07 '13 at 14:46
  • 1
    If you do nothing between timer events, then you can use e.g. `nanosleep`, then your process will simply do nothing (including not taking any CPU) until the sleep is over. If you want to do things while the timer is running, then the POSIX timer events is what you want. – Some programmer dude Oct 07 '13 at 14:59
  • One question: You said, "I've seen solutions using `sleep()` but it does not seem to be the best option for the job." - Why exactly? – ArjunShankar Oct 07 '13 at 15:06
  • How accureate can timers be in embedded system with OS (Linux in this case)? – user140345 Jul 26 '21 at 23:20

2 Answers2

3

I suggest consider using the poll(2) multiplexing syscall to do the polling.

notice that when poll is waiting and polling for input, it does not consume any CPU

If the processing of each event takes some significant time (e.g. a millisecond or more) you may want to recompute the delay.

You could use timerfd_create(2) (and give both your device file descriptor and your timer fd to poll). See also timer_create(2)...

Perhaps clock_gettime(2) could be useful.

And reading time(7) is definitely useful. Perhaps also the Advanced Linux Programming book.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
2

sleep() suspends execution in seconds, if you are looking for a more accurate sleep()-like function, use usleep() which suspends execution in microseconds, or nanosleep() in nanoseconds.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294