fcntl()函数之非阻塞模型

优点:设置标准输入为非阻塞(有数据则读 没有数据则立即返回),常用于网络通信以及轻量信息多并发中

步骤:

1.oldflag=fcntl(STDIN_FILENO,F_GETFL);

  获取标准输入的文件打开标志。

2.fcntl(STDIN_FILENO,F_SETFL,oldflag|O_NONBLOCK)

  将该标志加入O_NONBLOCK非阻塞标志

3.编写函数逻辑,以及要处理问题。

4.代码如下

//非阻塞模型
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(void)
{
char *t,buf[4096];

//设置标准输入为非阻塞(有数据则读 没有数据则立即返回)
int ret,oldflag;
oldflag=fcntl(STDIN_FILENO,F_GETFL);
if(oldflag==-1) return 1;//error!!!
if(fcntl(STDIN_FILENO,F_SETFL,oldflag|O_NONBLOCK)==-1)
{
perror("set no block ");
return 2;
}

while(1)
{
t=fgets(buf,4096,stdin);//getchar scanf read ==>stdin
if(t==NULL){
printf("非阻塞返回. ");
}else{
printf("buf>>>%s ",buf);
}

printf("do other. ");
usleep(500000);//0.5s
}

return 0;
}

////////////////////////////////////////////////////////利用阻塞错误、、、、、、、、、、、、、、

//非阻塞模型
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>//使用errno错误标记变量

int main(void)
{
char buf[4096+1];

//设置标准输入为非阻塞(有数据则读 没有数据则立即返回)
int ret,oldflag;
oldflag=fcntl(STDIN_FILENO,F_GETFL);
if(oldflag==-1) return 1;//error!!!
if(fcntl(STDIN_FILENO,F_SETFL,oldflag|O_NONBLOCK)==-1)
{
perror("set no block ");
return 2;
}

while(1)
{
ret=read(STDIN_FILENO,buf,4096);
if(ret==-1){//error
if(errno==EAGAIN)//非阻塞
{
printf("我要的非阻塞. ");
}
else
{
perror("read from stdin error");
return 3;
}
}else{
printf("buf>>>%s ",buf);
}

printf("do other. ");
usleep(500000);//0.5s
}

return 0;
}

原文地址:https://www.cnblogs.com/edan/p/8833585.html