Linux定时器 select(微秒精度)poll(毫秒精度)

8 篇文章 1 订阅
8 篇文章 0 订阅

头文件与函数

#include <sys/select.h>

int select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);

void FD_CLR(int fd, fd_set *set); //将set中第fd位清除

int FD_ISSET(int fd, fd_set *set);//判断set中第fd位是否位1,是返回1否返回1

void FD_SET(int fd, fd_set *set); //将set中第fd位设置为1

void FD_ZERO(fd_set *set);//将fd中所有位清除

fd_set可以看成一个数组,里面存着文件描述符。

readfds可读文件描述符集合

witefds可写文件描述符集合

execeptfds可执行文件描述符集合

n:所有集合中最大的文件描述符加1

struct timeval{      
                long tv_sec;   /*秒 */
                long tv_usec;  /*微秒 */   
            }
timeout表示select函数等待时间。
将select函数第一个参数设置为0,第二三四参数设置为NULL,最后一个参数设置为时间,可以当定时器用。
struct timeval tv;

tv.tv_sec = 1;

tv.tv_usec = 1000;
select(0, NULL, NULL, NULL, &tv);
实例,每0.5s执行一次函数

#include <sys/time.h>
#include <sys/select.h>
#include <stdio.h>
//mseconds: micro seconds 1s = 1000000us
void setTimer(int seconds, int useconds)
{
	struct timeval temp;

	temp.tv_sec = seconds;
	temp.tv_usec = useconds;

	select(0, NULL, NULL, NULL, &temp);
	printf("timer interval: %ds %dus\n", seconds, useconds);
	return;
}

int main()
{
	int i;
	for (i=0; i<10; i++)
	{
		setTimer(0, 500000);
	}
	return 0;
}	

使用poll()来作为毫秒精度定时器

原理与select一样,都是监视空文件描述符并等待超时。

#include <sys/time.h>
#include <stdio.h>
#include <poll.h>

//mseconds: 定时器毫秒
void setPollTimer(int mseconds)
{
	struct pollfd fds[1];
	fds[0].fd = 0;
	fds[0].events = POLLIN;
	poll(fds, 1, mseconds);
	printf("this is poll timer\n");
}

int main()
{
	int i;
	for (i=0; i<10; i++)
	{
		setPollTimer(2000);
	}
	return 0;
}	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值