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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值