生活随笔
收集整理的這篇文章主要介紹了
嵌入式Linux基础学习笔记-文件IO编程-I/O多路复用
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
實(shí)驗(yàn)內(nèi)容:多路復(fù)用—I/O操作及阻塞
- 編程實(shí)現(xiàn)文件描述符集合的監(jiān)聽(tīng)
multiplex_poll.c文件編寫:
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <poll.h>#define MAX_BUFFER_SIZE 1024
#define IN_FILES 3
#define TIME_DELAY 60
#define MAX(a, b) ((a > b)?(a):(b))int main(void)
{struct pollfd fds
[IN_FILES
];char buf
[MAX_BUFFER_SIZE
];int i
, res
, real_read
, maxfd
;fds
[0].fd
= 0;if((fds
[1].fd
= open
("in1", O_RDONLY
|O_NONBLOCK
)) < 0){printf("Open in1 error\n");return 1;}if((fds
[2].fd
= open
("in2", O_RDONLY
|O_NONBLOCK
)) < 0){printf("Open in2 error\n");return 1;}for (i
= 0; i
< IN_FILES
; i
++){fds
[i
].events
= POLLIN
;}while(fds
[0].events
|| fds
[1].events
|| fds
[2].events
){if (poll(fds
, IN_FILES
, 0) < 0) {printf("Poll error\n");return 1;}for (i
= 0; i
< IN_FILES
; i
++){if (fds
[i
].revents
){memset(buf
, 0, MAX_BUFFER_SIZE
);real_read
= read(fds
[i
].fd
, buf
, MAX_BUFFER_SIZE
);if (real_read
< 0){if (errno
!= EAGAIN
){return 1;}}else if (!real_read
){close(fds
[i
].fd
);fds
[i
].events
= 0;}else{if (i
== 0){if ((buf
[0] == 'q') || (buf
[0] == 'Q')){return 1;}}else{buf
[real_read
] = '\0';printf("%s", buf
);}} } } } exit(0);
}
運(yùn)行時(shí),需要打開(kāi)3個(gè)虛擬終端,分別創(chuàng)建兩個(gè)管道文件in1和in2,運(yùn)行主程序
終端1:
mknod in1 p
cat >in1
multiplex call
test in1
end
終端2:
mknod in2 p
multiplex call
test in2
end
終端3:
./multiplex_poll
總結(jié)
以上是生活随笔為你收集整理的嵌入式Linux基础学习笔记-文件IO编程-I/O多路复用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。