-2

我需要能够使用 C/C++ 在 Linux 上以不同的时间间隔调用某些函数。最好的方法是什么?例如,我想在 100hz 调用 a(),在 10hz 调用 b(),在 1hz 调用 c()。

4

2 回答 2

1

You could use Posix timers, i.e. timer_create(2) and timer_settime(2). Then you want to set a signal handler using sigaction(2). Be aware that signal handler functions are only allowed to call a very restricted set of functions (only the async-signal-safe functions, but even not fprintf or malloc!), see signal(7) and consider simply setting a volatile sigatomic_t variable in your signal handler (and test it appropriately outside).

You might instead having some event loop (e.g. libev, or making your own one with a multiplexing syscall like poll(2) etc...). If you are coding a graphical application (using e.g. Qt or Gtk) you already have an event loop, so use it (and you also have timers provided by the graphical toolkit or the event loop functions).

You may also want to look at timerfd_create(2) and friends (and use that fle descriptor in your event loop or poll(2) call).

Reading Advanced Linux Programming should help.

PS. Getting a reliable 100Hz (or slighly higher) timer frequency might be difficult with old kernels and old machines. You may want CONFIG_HIGH_RES_TIMERS=y and CONFIG_TIMERFD=y and CONFIG_HPET_TIMER=y and CONFIG_HZ_1000=y in the .config fle of your recent kernel.

于 2013-04-18T14:08:55.233 回答
1

您可以重复使用settimer来安排下一个具有最近截止日期的函数调用。

于 2013-04-18T13:37:06.133 回答