博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
笔记:非阻塞读终端和等待超时
阅读量:6948 次
发布时间:2019-06-27

本文共 1432 字,大约阅读时间需要 4 分钟。

hot3.png

#include 
#include 
#include 
#include 
#include 
#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)); else write(STDOUT_FILENO, buf, n); close(fd); return 0;}

实现以非阻塞方式打开终端I/O的第二种方式

#include 
#include 
#include 
#include 
#include 
#define MSG_TRY "try again\n"int main(void){    char buf[10];    int n;    int flags;    flags = fcntl(STDIN_FILENO, F_GETFL);    flags |= O_NONBLOCK;    if (fcntl(STDIN_FILENO, F_SETFL, flags) == -1)    {        perror("fcntl");        exit(1);    }tryagain:    n = read(STDIN_FILENO, buf, 10);    if (n < 0)    {        if (errno == EAGAIN)        {            sleep(1);            write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));            goto tryagain;        }        perror("read stdin");        exit(1);    }    write(STDOUT_FILENO, buf, n);    return 0;}

转载于:https://my.oschina.net/lovewxm/blog/214409

你可能感兴趣的文章
月薪13k的我为什么要转行学Python?
查看>>
节假日是不是一票难求?Python百十行代码帮你实现自动抢票!
查看>>
git 常见错误解决方案集合
查看>>
互联网架构技术面试题——Spring专题面试锦集
查看>>
GMQ打造区块链行业完整产业链,为区块链数字资产发展贡献一份力量
查看>>
js柯里化二三事
查看>>
iOS开发中的AOP利器 - Aspects 源码分析(二)
查看>>
写给自己看的 Flex 布局
查看>>
【译】CSS遮罩实现过渡效果
查看>>
巨杉中标渤海银行,股份制银行再下一城
查看>>
线性代数及其应用
查看>>
如何选择合适的数据库?
查看>>
Go:错误 could not launch process: EOF 解决
查看>>
CSS解决父子元素margin-top重叠问题
查看>>
redis消息队列简单应用
查看>>
android发送短信验证码并自动获取验证码填充文本框
查看>>
App 是否真的能检测手机壳颜色?
查看>>
学Hadoop还是Spark好?
查看>>
微服务生命周期的9个任务事项
查看>>
实战Kafka ACL机制
查看>>