Linux文件属性设置 -- fcntl函数

来源:互联网 发布:tcp端口号 编辑:程序博客网 时间:2024/05/22 15:25

fcntl功能

用fcntl函数改变一个已打开的文件的属性,可以重新设置读、写、追加、非阻塞等标志(这
些标志称为File Status Flag),而不必重新open文件。

#include <unistd.h>#include <fcntl.h>int fcntl(int fd, int cmd);int fcntl(int fd, int cmd, long arg);int fcntl(int fd, int cmd, struct flock *lock);

这个函数和open一样,也是用可变参数实现的,可变参数的类型和个数取决于前面的cmd参数。


用fcntl改变文件状态属性

因为STDIN_FILENO在程序启动时已经被自动打开了,而我们需要在调用open时指定O_NONBLOCK标志。
使用F_GETFLF_SETFL这两种fcntl命令改变STDIN_FILENO的属性

#include <stdlib.h>#include <unistd.h>#include <errno.h>#define MSG "hey guys how are you\n"int main(){    char buf[10];    int n, flags;    flags = fcntl(STDIN_FILENO, F_GETFL);    flags |= O_NONBLOCK;//添加上非阻塞属性    if(fcntl(STDIN_FILENO, F_SETFL, flags) == -1){ //设置属性        perror("fcntl");        exit(1);    }tryagain:    n = read(STDIN_FILENO, buf, 10);    if (n < 0) {        if (errno == EAGAIN) {            sleep(1);            write(STDOUT_FILENO, MSG, strlen(MSG));            goto tryagain;        }        perror("read stdin");        exit(1);    }    write(STDOUT_FILENO, buf, n);    return 0;}
0 0