#include <iostream>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <error.h>
bool SetNonBlock(int fd)
{
int fl = fcntl(fd, F_GETFL);
if (fl < 0)
return false;
fcntl(fd, F_SETFL, fl | O_NONBLOCK);
return true;
}
int main()
{
SetNonBlock(0);
char buffer[1024];
memset(buffer, 0, sizeof buffer);
while (true)
{
sleep(1);//让打印信息频率慢下来
errno = 0;
int s = read(0, buffer, sizeof(buffer) - 1);
if (s > 0)
{
buffer[s - 1] = 0;//不要让读取回车键,这样就能不换行
std::cout << "echo# " << buffer << " errno[----]: " << errno << " errstring: " << strerror(errno) << std::endl;
}
else
{
// std::cout << "read \"error\"" << " errno: " << errno << " errstring: " << strerror(errno) << std::endl;
if (errno == EWOULDBLOCK || errno == EAGAIN)
{
std::cout << "当前0号fd数据没有就绪, 请下一次再来试试吧" << std::endl;
continue;
}
else if (errno == EINTR)
{
std::cout << "当前IO可能被信号中断, 再试一次吧" << std::endl;
continue;
}
else
{
//进行差错处理
}
}
}
}
进行非阻塞读取的代码结构
最新推荐文章于 2024-07-19 17:07:49 发布