Linux:dup、dup2 、fcntl 函数

dup、dup2函数

在这里插入图片描述

dup

dup() 系统调用创建文件描述符 oldfd 的副本,使用编号最小的未使用文件描述符作为新描述符。

/*
#include <unistd.h>
int dup(int oldfd);
作用:
    复制一个新的文件描述符,指向同一个文件。
        fd=3, int fd1 = dup(fd);
        fd1与fd指向同一个文件。且fd1选择空闲的文件描述符中最小的一个

int dup2(int oldfd, int newfd);


*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <string.h>

int main(){
    
    

    int fd = open("b.txt", O_RDWR | O_CREAT, 0664);

    int fd1 = dup(fd);

    if(fd1 == -1){
    
    
        perror("dup");
        return -1;
    }

    printf("fd : %d, fd1 : %d \n",fd, fd1);

    close(fd);

    char *str = "hello world!";
    int ret = write(fd1, str, strlen(str));
    if(ret == -1){
    
    
        perror("write");
        return -2;
    }

    close(fd1);

    return 0;
}

dup2

dup2() 系统调用执行与 dup() 相同的任务,但它不使用编号最低的未使用文件描述符,而是使用 newfd 中指定的文件描述符编号。 如果文件描述符 newfd 先前已打开,则它会默认在重新使用之前关闭。

在这里插入图片描述

fcntl

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

int fcntl(int fd, int cmd, ...);
参数:
    - fd :
        表示需要操作的文件描述符cmd:表示对文件描述符进行如何操作
    - F_DUPFD :
        复制文件描述符,复制的是第一个参数fd,得到一个新的文件描述符(返回值)
        int ret = fcntl(fd,F_DUPFD);
    - F_GETFL :
        获取指定的文件描述符文件状态flag
        获取的flag和我们通过open函数传递的flag是一个东西。
    - F_SETFL :
        设置文件描述符文件状态flag
        必选项:O_RDONLY,O_WRONLY,O_RDWR 不可以被修改
        可选性:O_APPEND,O)NONBLOCKO_APPEND表示追加数据
            NONBLOK设置成非阻塞
            阻塞和非阻塞:描述的是函数调用的行为。
*/

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

#include <string.h>

int main(){
    
    

    int fd = open("c.txt", O_CREAT | O_RDWR, 0664);

    //1 复制文件描述符
    int ret = fcntl(fd, F_DUPFD);

    if(ret == -1){
    
    
        perror("fcntl");
        return -1;
    }

    printf("fd : %d, copy 's fd is: %d \n", fd, ret);
    close(fd);

    //2,修改或者获取文件状态的flags
    int fd1 = open("a.txt", O_RDONLY);

    //获取文件描述符的状态flag
    int flag = fcntl(fd, F_GETFL);
    flag |= O_APPEND;

    //修改文件状态的flag,给flag加入O_APPEND标记
    int ret1 = fcntl(fd1, F_SETFL, flag);

    char *str = "THIS IS CHINA";
    int retl = write(ret1, str, strlen(str));

    if(retl == -1){
    
    
        perror("write");
        return -1;
    }

    close(fd1);


    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44861043/article/details/121377288
今日推荐