定时等待I/O

定时等待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;
}

如果系统负载很严重,则可能发生定时器超时,则不再受定时器约束。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值