在使用标准库的读写操作函数时候,标准的接口是阻塞的,也就是说在没有完成动作之前,永远等待。在有些时候,我们对慢设备进行读写操作,需要有超时机制,如何实现呢?下面我简单的演示一种实现方法。
#include <iostream>
#include <unistd.h>
#include <assert.h>
#include <signal.h>
using namespace std;
#define INSTALL_TIMEOUT() install_signal( timeout, SIGALRM )
static struct sigaction oact;
static void timeout( int signum )
{
(void) signum;
// do nothing
}
static void install_signal( void (*sigHandler)( int ), int signum )
{
struct sigaction act;
sigemptyset( &act.sa_mask );
act.sa_handler = sigHandler;
act.sa_flags = 0;
int rs = sigaction( signum, &act, &oact );
assert( rs == 0 );
}
static int read_console( char *buf, int len, int
#include <iostream>
#include <unistd.h>
#include <assert.h>
#include <signal.h>
using namespace std;
#define INSTALL_TIMEOUT() install_signal( timeout, SIGALRM )
static struct sigaction oact;
static void timeout( int signum )
{
(void) signum;
// do nothing
}
static void install_signal( void (*sigHandler)( int ), int signum )
{
struct sigaction act;
sigemptyset( &act.sa_mask );
act.sa_handler = sigHandler;
act.sa_flags = 0;
int rs = sigaction( signum, &act, &oact );
assert( rs == 0 );
}
static int read_console( char *buf, int len, int