定时等待I/O
alarm()函数可以用来实现定时阻塞,当需要读写的设备未就绪时,只等待有限的时间。
该函数设置一个定时器,如果I/O系统调用超时,则会返回-1.
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
/* SIGALRM信号的处理函数 */
void alrm_handler(int signo)
{
/* 什么都不做,一个空的处理函数 */
}
/* 有限等待的read函数 */
size_t sig_read(int filefds, void *buf, size_t nbytes)
{
size_t n;
/* 加载SIGALRM的处理函数 */
if(signal(SIGALRM, alrm_handler) == SIG_ERR)
{
perror("fail to set handler for SIGALRM");
exit(1);
}
alarm(5); /* 设置定时器,只等待5秒钟 */
if((n = read(filefds, buf, nbytes)) == -1) /* 开始读操作,如果超时被中断,read函数返回-1 */
return -1;
alarm(0); /* 如果读成功,则取消定时器 */
return n;
}
有限等待write函数
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
/* SIGALRM信号的处理函数 */
void alrm_handler(int signo)
{
/* 什么都不做,一个空的处理函数 */
}
/* 有限等待的write函数,参数和返回值和read函数一样 */
size_t sig_read(int filefds, void *buf, size_t nbytes)
{
size_t n;
/* 加载SIGALRM的处理函数 */
if(signal(SIGALRM, alrm_handler) == SIG_ERR)
{
perror("fail to set handler for SIGALRM");
exit(1);
}
alarm(5); /* 设置定时器,只等待5秒钟 */
if((n = write(filefds, buf, nbytes)) == -1) /* 开始写操作,如果超时被中断,write函数返回-1 */
return -1;
alarm(0); /* 如果写成功,则取消定时器 */
return n;
}
如果系统负载很严重,则可能发生定时器超时,则不再受定时器约束。
相关文章
- JAVA之I/O 输入输出流详解
- c——I/O Multiplexing笔记
- I/O与主机交换信息有哪几种控制方式?各有何特点?
- python协程与异步I/O
- go get报错 i/o timeout的解决办法
- I/O复用-epoll模型
- 从阻塞到 Reactor:理解 Java I/O 背后的架构思维
- JAVA FILE or I/O学习 - 补充CopyFiles功能
- ResourceAccessException: I/O error on POST request for
- springboot使用TestRestTemplate单元测试时,提示ResourceAccess I/O error on POST request for "http