阻塞与否是文件的属性
- 普通文件默认不阻塞
- 终端设备:/dev/tty 默认阻塞
- 管道、套接字默认阻塞
举个栗子,下面利用非阻塞模式打开文件,然后不断循环读取缓冲区中的数据,如果没有数据则循环等待;
#include<unistd.h>
#include<fcntl.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MSG_TRY "try again\n"
//非阻塞读终端
int main(){
char buf[20];
int fd,n;
// /dev/tty 会自动指向当前打开的终端设备
fd = open("/dev/tty",O_RDONLY | O_NONBLOCK);
if(fd < 0)
{
perror("open /dev/tty");
exit(1);
}
tryagain:
n = read(fd,buf,20);
if(n < 0){
//文件被设置为非阻塞,当read时发现缓冲中没有数据可读,则全局变量errno会被设置为EAGAIN
if(errno == EAGAIN){
write(STDOUT_FILENO,MSG_TRY,strlen(MSG_TRY));
sleep(2);
goto tryagain;
}
perror("read /dev/tty");
exit(1);
}