Linux系统编程19-fcntl

fcntl是Linux中的一个系统调用,用于对文件描述符进行控制操作。其主要功能包括文件复制、文件描述符的获取和设置、非阻塞I/O等操作。

#include <unistd.h>
#include <fcntl.h>

int fcntl(int fd, int cmd, .../* arg */); // arg
    参数:
        fd : 需要操作的文件描述符
        cmd: 对文件描述符如何操作
            - F_DUPFD 复制文件描述符 ,返回一个新的文件描述符
                int ret = fcntl(fd, F_DUPFD);
            - F_GETFL 获取指定的文件描述符文件状态 flag
                获取的flag和通过open函数传递的flag是一个东西
            - F_SETFL 设置文件描述符文件状态flag
                必选 : O_RDONLY, O_WRONLY, O_RDWR 不可修改
                可选 : O_APPEND(追加数据), O_NONBLOCK(非阻塞)
                    阻塞与非阻塞: 描述的是函数调用的行为
         返回:执行成功或失败的状态。

实例:

fcntl.c

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char const *argv[])
{
    int fd = open("a.txt", O_RDWR);
    if (fd == -1)
    {
        perror("open err");
        return -1;
    }
    //复制文件描述符
    // int ret = fcntl(fd,F_DUPFD);

    //修改或者获取文件状态FLAG
    int flag = fcntl(fd, F_GETFL);
    //加入O_APPEND标记
    flag |= O_APPEND;
    int ret = fcntl(fd, F_SETFL, flag);
    if (ret == -1)
    {
        perror("fcntl err");
        return -1;
    }
    char *str = "\nnihao";
    write(fd, str, strlen(str));
    close(fd);

    return 0;
}
posted @ 2022-10-14 22:15  言叶以上  阅读(43)  评论(0编辑  收藏  举报