linux下用select实现精确到睡眠时间小于1秒的sleep函数

【说明:本文转自http://www.xuebuyuan.com/1585925.html
/*精确度为0.001秒的sleep函数*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/select.h>
 
void sleep_1(unsigned int secs)
{
  struct timeval tval;
  tval.tv_sec=secs/1000;
  tval.tv_usec=(secs*1000)%1000000;
  select(0,NULL,NULL,NULL,&tval);
}
 
//例如:调用sleep_1(500)时,表示睡眠0.5秒
//如果你觉得睡眠1秒时间太长,可以用此方法
//当然,如果你想要更精确的时间控制,可以进行修改:
/*
    tval.tv_sec=secs/1000000;
    tval.tv_usec=secs%1000000;
   
    精确度为1微秒(0.000001秒)
*/<span style="font-family: 'Microsoft YaHei', 微软雅黑, Arial, 'Lucida Grande', Tahoma, sans-serif; "> </span>
轮循: 一个无限循环..select最后一个参数 设置的很小 毫秒或者几秒的等待 有描述符准备好 则处理 继续循环.没有描述符准备好就结束.继续循环.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`select()` 是一个在 Linux 系统中提供的函数用于检查多个文件描述符(sockets、标准输入输出、文件等)是否处于可读、可写或者异常等状态。 函数原型如下: ```c #include <sys/select.h> int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); ``` 参数说明: - `nfds`:所有文件描述符集合中的最大描述符加 1。 - `readfds`:可读文件描述符的集合。 - `writefds`:可写文件描述符的集合。 - `exceptfds`:异常文件描述符的集合。 - `timeout`:超时时间,如果为 NULL,则表示一直等待。 函数返回值: - 大于 0:有文件描述符发生了变化,可以进行 I/O 操作。 - 等于 0:超时,没有文件描述符发生变化。 - 小于 0:发生错误。 在使用 `select()` 函数前,需要创建一个文件描述符集合,用 `FD_ZERO()` 函数将其全部清零,然后使用 `FD_SET()` 函数将需要检查的文件描述符添加到集合中。 示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <sys/select.h> #include <unistd.h> int main() { int fd[2]; pipe(fd); // 创建管道 fd_set readfds; FD_ZERO(&readfds); // 初始化集合 FD_SET(fd[0], &readfds); // 将读端添加到集合中 struct timeval timeout; timeout.tv_sec = 5; // 设置超时时间为 5 timeout.tv_usec = 0; int ret = select(fd[0] + 1, &readfds, NULL, NULL, &timeout); // 检查文件描述符是否可读 if (ret == -1) { perror("select error"); exit(EXIT_FAILURE); } else if (ret == 0) { printf("timeout\n"); } else { printf("fd[0] is ready for read\n"); } return 0; } ``` 上述代码中,使用了 `pipe()` 函数创建了一个管道,然后使用 `FD_ZERO()` 和 `FD_SET()` 函数初始化了文件描述符集合并将读端添加到集合中,最后使用 `select()` 函数检查文件描述符是否可读,如果超时则输出 "timeout",否则输出 "fd[0] is ready for read"。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值