1.废话不多说,直接上源码
需要包含的头文件
#include <sys/epoll.h>
#include <sys/timerfd.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> //open 头文件
#include <unistd.h> //close 头文件
2.定义epoll描述符epollfd,timer描述符timerfd
#define EPOLL_LISTEN_CNT 256
#define EPOLL_LISTEN_TIMEOUT 500
static int g_epollfd = -1;
static int g_timerfd = -1;
static int epoll_add_fd(int fd){
int ret;
struct epoll_event event;
memset(&event, 0, sizeof(event));
event.data.fd = fd;
event.events = EPOLLIN | EPOLLET;
ret = epoll_ctl(g_epollfd, EPOLL_CTL_ADD, fd, &event);
if (ret < 0){
return -1;
}
return 0;
}
static int epollfd_init(){
int epfd;
/* create epoll fd */
epfd = epoll_create(EPOLL_LISTEN_CNT);
if (epfd < 0){
return -1;
}
g_epollfd = epfd;
return epfd;
}
static int timerfd_init()
{
int tmfd;
int ret;
struct itimerspec new_value;
new_value.it_value.tv_sec = 0;
new_value.it_value.tv_nsec = 10 * 1000 * 1000;
new_value.it_interval.tv_sec = 0;
new_value.it_interval.tv_nsec = 10 * 1000 * 1000;
/* create timer fd */
tmfd = timerfd_create(CLOCK_MONOTONIC, 0);
if (tmfd < 0){
return -1;
}
ret = timerfd_settime(tmfd, 0, &new_value, NULL);
if (ret < 0){
close(tmfd);
return -1;
}
if (epoll_add_fd(tmfd)){
close(tmfd);
return -1;
}
g_timerfd = tmfd;
return 0;
}
3.两个用于,定义打印函数
void print_some_char(){
printf("hello world\n");
}
void print_timer_char(){
printf("this is timer\n");
}
4.main函数
int main(){
epollfd_init();
timerfd_init();
int i = 0;
int fd_cnt = 0;
int sfd;
struct epoll_event events[EPOLL_LISTEN_CNT];
int count = 0;
memset(events, 0, sizeof(events));
while(1) {
/* wait epoll event */
fd_cnt = epoll_wait(g_epollfd, events, EPOLL_LISTEN_CNT, EPOLL_LISTEN_TIMEOUT);
for (i = 0; i < fd_cnt; i++){
sfd = events[i].data.fd;
if (!(events[i].events & EPOLLIN)){
continue;
}
if (sfd != g_timerfd){
continue;
}
uint64_t exp;
read(sfd, &exp, sizeof(uint64_t));
//每次进来10ms,限制20ms一次
if ((count++) % 2 != 0){
continue;
}
print_timer_char();
print_some_char();
}
}
return 0;
}