1.阻塞(block)概念:指进程或线程在执行设备操作或管道,或则网络时,不能获取到资源就被挂起,
直到满足可操作的条件后在进行操作,被挂起的进程进入休眠状态,从运行队列移走,直到
等待的条件满足才继续执行。也就是执行到某些函数时必须等待某个事件发生函数才返回。
2.非阻塞(non_block):进程就算没有获取到资源或没有等到事件发生时不挂起,通常会直接放弃或不断查询,
直到可以进行的位置。也就是函数的执行不必等待事件发生,一旦执行肯定返回,用返回值来反应函数执行情况。
3.例如:read读取输入输出设备/dev/tty
4.read设备文件时发生阻塞
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[])
{
int fd = open("/dev/tty",O_RDONLY); //打开标准输入输出文件,此时为阻塞
if(fd == -1){
perror("open /dev/tty");
exit(1);
}
int ret = 0;
char buf[1024] = {0};
while(1){
ret = read(fd, buf, sizeof(buf));
if(ret == -1){
perror("read");
exit(1);
}
else if(ret == 0)
printf("buf is null\n");
else if(ret > 0)
printf("buf is %s\n",buf);
printf("test\n");
sleep(1);
}
close(fd);
return 0;
}
5.直接用O_NONBLOCK设置非阻塞
int main(int argc, char* argv[])
{
int fd = open("/dev/tty", O_RDONLY | O_NONBLOCK); // O_NONBLOCK 设置文件输入输出为非阻塞
if(fd == -1){
perror("open /dev/tty");
exit(1);
}
int ret = 0;
char buf[1024] = {0};
while(1){
ret = read(fd, buf, sizeof(buf));
if(ret == -1){
perror("read /dev/tty");
printf("no input,buf is null\n");
}
else {
printf("ret = %d, buf is %s\n",ret, buf);
}
sleep(1);
}
close(fd);
return 0;
}
6.用fcntl()函数与O_NONBLOCK设置非阻塞
int main(int argc, char* argv[])
{
int fd = open("/dev/tty", O_RDONLY);
//fcntl()函数设置标准输入输出文件为非阻塞
int flag = fcntl(fd, F_GETFL); //第一步:获取文件操作权限
flag |= O_NONBLOCK; //第二步:获取的文件属性与O_NONBLOCK相或
fcntl(fd, F_SETFL, flag); //第三步:再次设置文件操作权限
int ret = 0;
char buf[1024] = {0};
while(1){
ret = read(fd, buf, sizeof(buf));
if(ret == -1){
perror("read /dev/tty");
printf("no input,buf is null\n");
}
else {
printf("ret = %d, buf is %s\n",ret, buf);
}
sleep(1);
}
close(fd);
return 0;
}