定时等待I/O
2015-08-07 09:25
369 查看
定时等待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;
}
如果系统负载很严重,则可能发生定时器超时,则不再受定时器约束。
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;
}
如果系统负载很严重,则可能发生定时器超时,则不再受定时器约束。
相关文章推荐
- Myeclipse2014中,新建部署Maven项目
- 转载_如何像巫师那样隔空操作——聊聊迷你雷达的原理和应用
- 南邮 OJ 1810 A. The more the better
- 关于singleInstance做的测试(亲测and接上篇文章继续测试)
- STL vector的简单用法
- Eclipse中问题大汇总及方案!
- J2EE--Servlet生命周期与原理
- 不一样的控制面板 GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}
- PHP错误处理
- 如何在android style文件中使用自定义属性
- 创建mysql数据库
- ORACLE启动报错:ORA-16068:redo log file activation identifier mismatch
- 三十과 三十六
- mysql select语句
- JPA和Hibernate的区别
- Qt 4 迁移至 Qt 5
- 南邮 OJ 1799 比赛成绩查询问题
- 更复杂的滤镜
- java如何根本生成10位号(比如订单号)
- struts2工作机制详解