linux - 为什么我的计时器不是周期性的而是只过期一次?

标签 linux timer

我使用 POSIX timerfd 函数创建了一个计时器。 意图是,计时器应该是周期性的,计时器到期是从一个名为 myFunc( )

的单独函数中观察到的

我多次调用此函数,以便在等待 5 秒后可以定期观察到计时器到期。

问题是,一旦第一次在 5 秒后过期,下一次...它不会再次过期,即从第二次迭代开始没有观察到 5 秒的延迟。

谁能告诉我我错过了什么?

#include <stdio.h>
#include <iostream>
#include <errno.h>
#include <dlfcn.h>
#include <assert.h>
#include <sys/mman.h>
#include <new>

#include <limits.h>
#include <sys/epoll.h>
#include <sys/timerfd.h>

using namespace std;

struct epoll_event event;
int timer_fd, efd, no_of_fd;
void myFunc( int i );

int main()
{
  struct itimerspec its;

  its.it_value.tv_sec = 5;
  its.it_value.tv_nsec = 0;

  its.it_interval.tv_sec = 3; // Every 3 seconds interval
  its.it_interval.tv_nsec = 0;


  efd = epoll_create(2);
  timer_fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);

  if ( timer_fd == -1 )
  {
    fprintf(stderr, "timerfd_create error in start timer");
    return 1;
  }

  event.data.fd = timer_fd;
  event.events = EPOLLIN|EPOLLPRI;

  if ( epoll_ctl(efd, EPOLL_CTL_ADD, timer_fd, &event) == -1 )
  {
     fprintf(stderr, "epoll_ctl error in start timer"); 
     return 1;
  }

  if ( timerfd_settime(timer_fd, 0, &its, NULL) == -1 )
  {
    fprintf(stderr, "timerfd_settime error in start timer");
    return 1;
  }
  myFunc( 10 );
  myFunc( 20 );
  myFunc( 30 );
}

void myFunc( int i )
{
  printf("Inside myFunc %d\n", i);
  no_of_fd = 0;
  struct epoll_event revent;
  errno = 0;
  do {
     no_of_fd = epoll_wait(efd, &revent, 1, -1);
  } while ( no_of_fd < 0 && errno == EINTR );

  if ( no_of_fd < 0 )
  {
    fprintf(stderr, "epoll_wait error in start timer");

  }

  if ( revent.data.fd == timer_fd ) {
     printf("Timer expired \n");    
  }

}

最佳答案

当使用带电平触发的epoll 时,您应该在每个EPOLLIN 上读取8 个字节。这是一个 int64,告诉您事件过期的次数。读取它会有效地“清除”这个数字,以便下一个 EPOLLIN 是不同事件到期的结果。

手册告诉你关于阅读:

          If the timer has already expired one or more times since its
          settings were last modified using timerfd_settime(), or since
          the last successful read(2), then the buffer given to read(2)
          returns an unsigned 8-byte integer (uint64_t) containing the
          number of expirations that have occurred.  (The returned value
          is in host byte order—that is, the native byte order for
          integers on the host machine.)

关于linux - 为什么我的计时器不是周期性的而是只过期一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25804171/

相关文章:

c++ - 使用 QueryPerformanceCounter() 倒计时

windows - $相当于什么?在 Windows 中?

linux - 将 nslookup 的结果放入列中

linux - 脚本不执行,而是挂起

java - 以给定的执行时间启动线程

python - Python 中的快速方法调用调度

JDialog 中的 javax.swing.Timer 在关闭 JDialog 时不会停止

php - 检查用户是否在其他设备上登录

linux - 如何在 linux 中不解压文件的情况下列出文件的前 10 行或后 10 行

linux - 不同 openssl 版本的行为差异