目录
2.epoll监听timerfd时,需保证epollfd和timerfd在同一个进程
一,使用问题总结
有关epoll和timerfd的基础请自行补充,这里先讲一下调试过程中遇到的问题和解决办法。
1.linux的句柄是进程生效的
不同的进程有不同的fd,如果对这句话没有更深入的理解,可以看后续几条
查看不同进程fd的命令
ls -l /proc/pid/fd
root@localhost:~# ls -l /proc/2374/fd
total 0
lrwx------ 1 root root 64 Jan 6 09:50 0 -> /var/log/tos_configd.log
lrwx------ 1 root root 64 Jan 6 09:50 1 -> /var/log/tos_configd.log
lrwx------ 1 root root 64 Jan 6 09:50 10 -> anon_inode:[eventpoll]
lrwx------ 1 root root 64 Jan 6 09:50 11 -> /dev/uio2
lrwx------ 1 root root 64 Jan 6 09:50 12 -> /sys/devices/pci0000:00/0000:00:14.0/config
lrwx------ 1 root root 64 Jan 6 09:50 13 -> /dev/uio3
lrwx------ 1 root root 64 Jan 6 09:50 14 -> /sys/devices/pci0000:00/0000:00:14.1/config
lrwx------ 1 root root 64 Jan 6 09:50 15 -> /dev/uio4
lrwx------ 1 root root 64 Jan 6 09:50 16 -> /sys/devices/pci0000:00/0000:00:14.2/config
lrwx------ 1 root root 64 Jan 6 09:50 17 -> /dev/uio5
lrwx------ 1 root root 64 Jan 6 09:50 18 -> /sys/devices/pci0000:00/0000:00:14.3/config
lrwx------ 1 root root 64 Jan 6 09:50 19 -> /dev/uio6
lrwx------ 1 root root 64 Jan 6 09:50 2 -> /var/log/tos_configd.log
2.epoll监听timerfd时,需保证epollfd和timerfd在同一个进程
3.timerfd相关的几个函数
timerfd_create,timerfd_settime,timerfd_gettime涉及到的fd需要在同一个进程中,否则操作会失败或者后果无法预测
#include <sys/timerfd.h>
int timerfd_create(int clockid, int flags);
参数:
clockid : 参考 clock_gettime 篇章
flags : 可以设置的位如下
TFD_NONBLOCK: 非阻塞模式
TFD_CLOEXEC: 表示当程序执行exec函数时本fd将被系统自动关闭,表示不传递
enum
{
TFD_CLOEXEC = 02000000,
#define TFD_CLOEXEC TFD_CLOEXEC
TFD_NONBLOCK = 00004000
#define TFD_NONBLOCK TFD_NONBLOCK
};
返回值:
成功返回新的文件描述符,失败返回-1并设置errno
int timerfd_settime(int fd, int flags,
const struct itimerspec *new_value,
struct itimerspec *old_value);
参数:
fd : 是timerfd_create函数返回的文件句柄
flags : 为1 代表设置的是绝对时间( TFD_TIMER_ABSTIME 为 1)
为0 以启动相对计时器(new_value.it_value指定相对于由clockid指定的时钟的当前值)
new_value : 指定定时器的超时时间以及超时间隔时间
it_interval不为0则表示是周期性定时器
it_value和it_interval都为0表示停止定时器
old_value : 如果old_value不为NULL, old_vlaue返回之前定时器设置的超时时间
返回值:
成功返回0,失败返回-1 并设置errno
int timerfd_gettime(int fd, struct itimerspec *curr_value);
参数:
fd : 是timerfd_create函数返回的文件句柄
curr_value : curr_value.it_value 字段表示距离下次超时的时间,如果改值为0,表示计时器已经解除
该字段表示的值永远是一个相对值,无论TFD_TIMER_ABSTIME是否被设置
curr_value.it_interval 定时器间隔时间
返回值:
成功返回0,失败返回-1 并设置errno
struct timespec {
time_t tv_sec; /* Seconds */
long tv_nsec; /* Nanoseconds */
};
struct itimerspec {
struct timespec it_interval; /* Interval for periodic timer */ (定时间隔周期)
struct timespec it_value; /* Initial expiration */ (第一次超时时间)
};
可以用read函数读取计时器的超时次数
uint64_t exp = 0;
read(fd, &exp, sizeof(uint64_t));
二 代码实现
待续