Skip to content

Instantly share code, notes, and snippets.

@zheplusplus
Created November 12, 2015 02:37
Show Gist options
  • Save zheplusplus/20b9f6e5bed454e19777 to your computer and use it in GitHub Desktop.
Save zheplusplus/20b9f6e5bed454e19777 to your computer and use it in GitHub Desktop.
C timer example
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/timerfd.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
void setnonblock(int sockfd)
{
int opts;
opts = fcntl(sockfd, F_GETFL);
if (opts < 0) {
perror("GETFL");
}
opts = (opts | O_NONBLOCK);
if (fcntl(sockfd, F_SETFL, opts) < 0) {
perror("SETFL");
}
}
int main()
{
int efd =epoll_create(256);
setnonblock(efd);
struct epoll_event ev, events[256];
int i;
int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
if (tfd < 0) {
perror("timer create");
return 1;
}
struct itimerspec newValue;
struct itimerspec oldValue;
memset(&newValue, 0, sizeof newValue);
memset(&oldValue, 0, sizeof oldValue);
struct timespec ts;
ts.tv_sec = 5;
ts.tv_nsec = 0;
newValue.it_value = ts;
newValue.it_interval = ts;
if (timerfd_settime(tfd, 0, &newValue, &oldValue) < 0) {
perror("settime");
return 1;
}
ev.data.fd = tfd;
ev.events = EPOLLIN | EPOLLET;
if (epoll_ctl(efd, EPOLL_CTL_ADD, tfd, &ev) < 0) {
perror("epoll add");
return 1;
}
int num = 0;
while (1) {
if ((num=epoll_wait(efd, events, 256, 1000)) > 0) {
for (i = 0; i < num; i++) {
if (events[i].data.fd == tfd) {
printf("timeout\n");
if (timerfd_settime(tfd, 0, &newValue, &oldValue) < 0) {
perror("settime");
return 1;
}
if (epoll_ctl(efd, EPOLL_CTL_MOD, tfd, &ev) < 0) {
perror("epoll add");
return 1;
}
}
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment