分类: C/C++
2007-01-13 11:38:06
同过select对/dev/tty /dev/mouse 进行监视,看是否有输入动作。
#include
#include
#include
#include
#include
#define ERR(m,x) { perror(m); exit(x); }
main(int ac, char* av[])
{
int fd1, fd2;
struct timeval timeout;
fd_set readfds;
int maxfd;
int retval; //select return value
if( ac != 4 )
{
printf( "usage: %s file file timeout", *av );
exit(1);
}
if( (fd1 = open(av[1], O_RDONLY) ) == -1 )
ERR(av[1], 2 );
if( (fd1 = open(av[2], O_RDONLY) ) == -1 )
ERR(av[2], 3 );
maxfd = 1 + (fd1 〉fd2? fd1:fd2 ) ;
while(1)
{
FD_ZERO( &readfds );
FD_SET( fd1, &readfds);
FD_SET( fd2, &readfds);
timeout.tv_sec = atoi( av[3] ); //set seconds
timeout.tv_usec = 0; //no useconds
//wait for input
retval = select ( maxfd, &readfds, &timeout );
if( -1 == retval )
ERR( "select", 4 );
if( retval > 0 )
{
if( FD_ISSET(fd1, &readsets))
showData( av[1], fd1 );
if( FD_ISSET(fd2, &readsets))
showData( av[2], fd2);
}
else
printf("No input after %d seconds\n", atoi(av[3]) );
}
}
void showData( char* fname, int fd )
{
char buffer[1024];
int n;
printf("In file %s\n", fname);
fflush(stdout);
n = read( fd, buffer, 1024 )
if ( n == -1 )
ERR("read", 5 );
write( 1, buffer, n);
write( 1, "\n", 1 );
}