阻塞和非阻塞描述的是线程的状态
同步异步描述的是编程的方式
●阻塞:调用函数的结果返回前,当前进程(线程)会被挂起,直到得到结果才会继续运行。
●非阻塞:调用函数后会直接返回结果,不会等待结果。
open()打开文件时可以通过参数O_NONBLOCK
设置文件为非阻塞模式:
普通文件默认是非阻塞的,内核缓冲区保证了普通文件IO不会发生阻塞事件,所以普通文件不需要考虑是否阻塞
设备、管道和套接字默认是阻塞的,以O_NONBLOCK
方式打开可以做非阻塞IO (NonblockI/O)
。
阻塞模式标准输入:
char buf [ 1024];
int read_count = read(0, buf, sizeof (buf));
printf("read count = %d\n", read_count);
write(1, buf, read_count);
非阻塞模式打开终端:
char buf [ 1024];
int read_count = read(0, buf, sizeof (buf));
printf("read count = %d\n", read_count);
write(1, buf, read_count);
perror
会把errno
对应的报错信息给打出来
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>
#include<fcntl.h>
#include<errno.h>
int main(int argc, char* argv[])
{
int fd = open("dev/fd/0", O_RDWR | O_NONBLOCK);
char buf[1024];
int read_count = read(fd, buf, sizeof(buf));
printf("read_count = %d, errno = %d\n", read_count, errno);
return 0;
}