您的位置:首页 > 其它

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

}

如果系统负载很严重,则可能发生定时器超时,则不再受定时器约束。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: