阻塞的概念:
read函数在读设备或者读管道,或者读网络的时候,
输入输出设备对应/dev/tty
read_tty.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
//int fd=open("/dev/tty",O_RDWR|O_NONBLOCK);
int fd=open("/dev/tty",O_RDWR);
//fcntl函数,设置非阻塞
int flags=fcntl(fd,F_GETFL);
flags |=O_NONBLOCK;
fcntl(fd,F_SETFL,flags);
int ret=0;
while(1){
read(fd,buf,sizeof(buf));
if(ret<0){
perror("read err:");
printf("ret is %d\n",ret);
if(ret){
printf("buf is %s\n",buf);
}
printf("haha\n");
sleep(1);
}
close(fd);
return 0;
}
本文探讨了如何在C语言中使用`read`函数从/dev/tty设备读取数据时设置非阻塞模式,通过`fcntl`函数实现低延迟通信,展示了在while循环中处理read返回值的实例。
108

被折叠的 条评论
为什么被折叠?



