fcntl改文件属性

代码

/*************************************************************************
	> File Name: fcntl.c
	> Author: shaozheming
	> Mail: 957510530@qq.com
	> 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会得到文件的属性,加上又是位图,所以或上之后会改变相应的位图。

posted @   蘑菇王国大聪明  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示