在Linux中周期性任务 [英] Periodic Task in Linux

查看:344
本文介绍了在Linux中周期性任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个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?

推荐答案

您应该阅读的时间(7)(也许信号(7 ) ...)。你可能需要一些事件循环(至少如果你的程序做一些输入)。这个循环是基于如调查(2)复用系统调用(见答案)。许多图书馆提供事件循环,尤其是的libevent ,的 libev ,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上,你可以的的通过的 timerfd_create(2)(除了其他更传统的解决方案)。

On Linux you could be also interested by timerfd_create(2) (in addition of other more traditional solutions).

和阅读高级Linux编程

这篇关于在Linux中周期性任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆