代码

/*************************************************************************
> File Name: fcntl.c
> Author: shaozheming
> Mail:
> Created Time: 2022年02月25日 星期五 09时26分46秒
************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <fcntl.h>
#include <errno.h>

#define MSG_TRY "try again! \r\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");
exit(1);
}
flags |= O_NONBLOCK;//向文件加入非阻塞的信息
int ret = fcntl(STDIN_FILENO, F_SETFL, flags);//然后再加入回去,等于是修改了文件属性
if(ret == -1){
perror("fcntl error");
exit(1);
}

tryagain:
n = read(STDIN_FILENO, buf, 10);
if(n < 0){
if(errno != EAGAIN){
perror("read /dev/tty");
exit(1);
}
sleep(3);
write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));
goto tryagain;
}
write(STDOUT_FILENO, buf, n);

return 0;
}

注意里面有一个flags位图,这个图表是以一个二进制位表示的。为了节约内存。
fcntl的返回值flags会得到文件的属性,加上又是位图,所以或上之后会改变相应的位图。

主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈