将文件描述符设置为非阻塞,可以采用fcntl
接口
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd, ... /* arg */ );
一下采用F_GETFD
,先获取文件描述符的标记,然后再添加非阻塞选项
#include<iostream>
#include<unistd.h>
#include<fcntl.h>
#include<cstdio>
#include<cstring>
#include<cerrno>
using namespace std;
void SetNOBlock(int fd)
{
int fl = fcntl(fd, F_GETFD); //获取文件描述符标记
if(fl < 0) //获取失败
{
perror("fcntl");
return;
}
fcntl(fd, F_SETFL, fl | O_NONBLOCK); //添加非阻塞选项
cout << "set " << fd << " non block success" << endl;
}
int main()
{
char buffer[1024];
SetNOBlock(0);
sleep(1);
while(true)
{
// printf("Please Enter: ");
// fflush(stdout);
ssize_t n = read(0, buffer, sizeof(buffer)-1);
if(n > 0)
{
buffer[n-1] = 0;
cout << "echo: " << buffer << endl;
}
else if(n == 0)
{
cout << "read done" << endl;
break;
}
else
{
if(errno == EWOULDBLOCK)
{
cout << "0 fd data not ready, please try again" << endl;
sleep(1);
}
else
{
cerr << "read error, fd = " << n << ", erron code: " << errno << " error str:" << strerror(errno) << endl;
break;
}
}
}
return 0;
}
当
read
的错误码为11(EWOULDBLOCK)
时,表示当前文件描述符数据没有就绪