问题描述
我想写一个C程序将定期执行某些任务(例如,在控制台上打印的东西)。
I want to write a C program that would periodically perform some task (say, print something on console).
我下面使用了nanosleep付诸实施。每500ms的功能'功能'之称。
I have implemented it using nanosleep as below. Every 500ms the function 'func' is called.
#include <stdio.h>
#include <time.h>
void func(void);
int main()
{
struct timespec mytimespec;
mytimespec.tv_sec = 0;
mytimespec.tv_nsec = 500000000; /* 500 ms */
while(1)
{
func();
nanosleep(&mytimespec,NULL);
}
return 0;
}
void func(void)
{
printf("This would be printed periodically\n");
}
以上工作正常。但是我有些疑惑: -
Above is working correctly. However I have some doubts:-
-
如果有多个线程和一个线程依赖于
了nanosleep
做周期性任务难道准确工作?
Would it work accurately if there are multiple threads and one thread relies on
nanosleep
to do the periodic task?
有没有办法产卵在linux周期性线程?或者使用一些定时器的回调?
Is there a way to spawn a periodic thread in linux? Or, to use some timer callback?
推荐答案
您应该阅读的(也许 ...)。你可能需要一些(至少如果你的程序做一些输入)。这个循环是基于如复用系统调用(见和答案)。许多图书馆提供事件循环,尤其是,的,GTK /巧舌如簧,Qt的,...
You should read time(7) (and perhaps signal(7)...). You probably want some event loop (at least if your program is doing some input). That loop is based upon a multiplexing syscall like poll(2) (see also this and that answers). Many libraries provide event loops, notably libevent, libev, Gtk/Glib, Qt, ...
在Linux上,你可以的也的通过的(除了其他更传统的解决方案)。
On Linux you could be also interested by timerfd_create(2) (in addition of other more traditional solutions).
和阅读
这篇关于在Linux中周期性任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!