您的位置:首页 > 其它

非阻塞轮询读终端和等待超时

2017-04-17 17:20 225 查看
1、非阻塞轮询读终端
#include <unistd.h>#include <fcntl.h>#include <errno.h>#include <string.h>#include <stdlib.h>#define MSG_TRY "try again\n"int main(void){char buf[10];int fd, n;fd = open("/dev/tty", O_RDONLY|O_NONBLOCK);if(fd<0) {perror("open /dev/tty");exit(1);}tryagain:n = read(fd, buf, 10);if (n < 0) {if (errno == EAGAIN) {sleep(1);write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));goto tryagain;}perror("read /dev/tty");exit(1);}write(STDOUT_FILENO, buf, n);close(fd);return 0;}
2、非阻塞轮询读终端和等待超时#include <unistd.h>#include <fcntl.h>#include <errno.h>#include <string.h>#include <stdlib.h>#define MSG_TRY "try again\n"#define MSG_TIMEOUT "timeout\n"int main(void){char buf[10];int fd, n, i;fd = open("/dev/tty", O_RDONLY|O_NONBLOCK);if(fd<0) {perror("open /dev/tty");exit(1);}for(i=0; i<5; i++) {n = read(fd, buf, 10);if(n>=0)break;if(errno!=EAGAIN) {perror("read /dev/tty");exit(1);}sleep(1);write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));}if(i==5)write(STDOUT_FILENO, MSG_TIMEOUT, strlen(MSG_TIMEOUT));elsewrite(STDOUT_FILENO, buf, n);close(fd);return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: