2014年(41)
分类: C/C++
2014-05-04 21:18:06
IO多路复用就是一种能够同时监视多个文件描述符,当文件描述符可操作时通知程序,否则等待的一种机制。
1.
int select(int nfds, fd_set *readfds, fd_set *writefds,fd_set *exceptfds, struct timeval *timeout);
nfds:最大的文件描述符加1
readfds:读操作的文件描述符集合
writefds:写操作的文件描述符集合
exceptfds:要监视出错的文件描述符集合
timeout:超时时间
文件描述符集合操作:
void FD_CLR(int fd, fd_set *set);将一个文件描述符从set中清除
int FD_ISSET(int fd, fd_set *set);判断一个文件描述符是否在set中
void FD_SET(int fd, fd_set *set);将fd加入set中
void FD_ZERO(fd_set *set);将set清空
select函数每一次都要将要监视的文件描述符加入集合中,超时时间也要重新设置。
int pselect(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, const struct timespec *timeout,
const sigset_t *sigmask);
pselect函数:是在select的基础上,可对信号屏蔽字进行设置,以保证select执行过程中在不被信号中断。
8 #include
9 #include
10
11 /* According to earlier standards */
12 #include
13 #include
14 #include
15 #include
16 #include
17 #include
18
19 int main(int argc, char **argv)
20 {
21 int fdm;
22 fd_set rset;
23 char buf[128] = {0};
24 struct timeval tv;
25 int ret;
26
27 fdm = open("/dev/input/mouse1", O_RDONLY);
28 if(fdm == -1)
29 {
30 perror("open");
31 exit(1);
32 }
33
34 while(1)
35 {
36 FD_ZERO(&rset);
37 FD_SET(fdm, &rset);
38 FD_SET(0, &rset);
39 tv.tv_sec = 3;
40 tv.tv_usec = 22;
41
42 ret = select(fdm+1, &rset, NULL, NULL, &tv);
43 if(ret < 0)
44 {
45 perror("slect");
46 exit(1);
47 }
48 else if(ret == 0)
49 {
50 printf("timeout .......\n");
51 continue;
52 }
53 if(FD_ISSET(fdm, &rset))
54 {
55 memset(buf, 0, 128);
56 if(read(fdm, buf, 128) < 0)
57 perror("read");
58 printf("mouse: %s\n", buf);
59 }
60 if(FD_ISSET(0, &rset))
61 {
62 memset(buf, 0, 128);
63 read(0, buf, 128);
64 printf("keyboard: %s\n", buf);
65 }
66 }
67 close(fdm);
68 return 0;
69 }
2.
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
fds:要监视的文件描述符都加入这个结构体数组中
struct pollfd {
int fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
};
nfds:要监视的文件描述符个数
timeout:超时时间,以ms计
int ppoll(struct pollfd *fds, nfds_t nfds,
const struct timespec *timeout, const sigset_t *sigmask);
在poll基础上实现信号屏蔽字设置
8 #include
9 #include
10 #include
11 #include
12 #include
13 #include
14 #include
15 #include
16
17 int main()
18 {
19 int fdm;
20 int ret;
21 char buf[128];
22 struct pollfd pfd[2];
23
24 fdm = open("/dev/input/mouse1", O_RDONLY);
25 if(fdm < 0)
26 {
27 perror("open");
28 exit(1);
29 }
30 pfd[0].fd = fdm; /* file descriptor */
31 pfd[0].events = POLLIN; /* requested events */
32
33 pfd[1].fd = 0;
34 pfd[1].events = POLLIN;
35
36 while(1)
37 {
38 ret = poll(pfd, 2, 3000);
39 if(ret < 0)
40 {
41 perror("poll");
42 exit(1);
43 }
44 else if(ret == 0)
45 {
46 printf("timeout.....\n");
47 continue;
48 }
49
50 if(pfd[0].revents == POLLIN)
51 {
52 memset(buf, 0, 128);
53 read(fdm, buf, 128);
54 printf("mouse: %s\n", buf);
55 }
56 if(pfd[1].revents == POLLIN)
57 {
58 memset(buf, 0, 128);
59 read(0, buf, 128);
60 printf("keyboard: %s\n", buf);
61 }
62 }
63
64 close(fdm);
65 return 0;
66 }