普通文件不会阻塞
fcntl:
int flags = fcntl(fd, F_GETFL);
flags |= O_NONBLOCK; 位图–二进制位
int ret = fcntl(fd, F_SETFL, flags);
获取文件状态: F_GETFL
设置文件状态: F_SETFL
#icnlude <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#define MSG_TRY "try again\n"
int main(int argc, char *argv[])
{
char buf[10];
int flags, n;
flags = fcntl(STDIN_FILENO, F_GETFL); //获取文件属性
if(flags == -1
{
perror("fcntl error\n");
exit(1);
}
flags |= O_NONBLOCK; //文件属性附加 非阻塞
int ret = fcntl(STDIN_FILENO, F_SETFL, flags); //设置文件属性
if(ret == -1)
{
perror("f_setfl error");
exit(1);
}
n = read(STDIN_FILENO, buf, 10);
if(n < 0)
{
if(errno != EAGAIN)
{
perror("read error\n");
exit(1);
}
sleep(3);
write(STDOUT_FILENO,MSG_TRY, strlen(MSG_TRY));
goto tryagain;
}
write(STDOUT_FILENO, buf, n);
return 0;
}