• dup和dup2函数


    dup和dup2函数

    dupdup2用于复制文件描述符,通常用于重定向。

    #include 
    
    int dup(int oldfd);
    int dup2(int oldfd, int newfd);
    
    • 1
    • 2
    • 3
    • 4

    dup函数创建一个新的文件描述符,该新文件描述符和原有文件描述符oldfd指向相同的文件、管道或者网络连接。并且dup返回的文件描述符总是取系统当前可用的最小整数值。

    dup2dup类似,不过它将返回第一个不小于newfd的整数值的文件描述符,并且newfd这个文件描述符也将会指向oldfd指向的文件,原来的newfd指向的文件将会被关闭(除非newfdoldfd相同)。

    dupdup2系统调用失败时返回-1并设置errno,成功就返回新的文件描述符。

    注意:通过dup和dup2创建的文件描述符并不继承原文件描述符的属性,比如close-on-exec和non-blocking 等

    dup简单,输入oldfd直接返回复制的文件描述符

    #include 
    #include 
    #include 
    #include 
    #include 
    int main(int argc, char const *argv[])
    {
        int fd = open("text.txt", O_RDWR | O_CREAT, 0666);
        assert(fd != -1);
        printf("fd = %d\n", fd);
    
        int fd2 = dup(fd);
        printf("fd2 = %d\n", fd2);
    
        char str[] = "hello ";
        write(fd, str, sizeof(str));
        char str2[] = "world\n";
        write(fd2, str2, sizeof(str2));
    
        close(fd);
        close(fd2);
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    image-20220815171158327

    dup2感觉复杂一些,其实dup2忽略第二个参数,功能是和dup一样的,除此之外dup2加了一个将返回第一个不小于newfd的整数值的文件描述符的功能,并且newfd也将指向oldfd指向的文件。

    下面的代码调用dup2,文件描述符fd2原来指向"text2.txt"文件的,调用dup2后,fd2改为指向"text.txt"。

    image-20220815173243219

    #include 
    #include 
    #include 
    #include 
    #include 
    int main(int argc, char const *argv[])
    {
        int fd1 = open("text.txt", O_RDWR | O_CREAT, 0666);
        int fd2 = open("text2.txt", O_RDWR | O_CREAT, 0666);
    
        assert(fd1 != -1);
        assert(fd2 != -1);
        printf("fd1 = %d, fd2 = %d\n", fd1, fd2);
    
        int fd3 = dup2(fd1, fd2);
        printf("fd1 = %d,fd2 = %d,fd3 = %d\n", fd1, fd2, fd3);
    
        char str[] = "hello ";
        write(fd1, str, sizeof(str));
        char str2[] = "world\n";
        write(fd2, str2, sizeof(str2));
        char str2[] = " hello world\n";
        write(fd3, str2, sizeof(str2));
    
        close(fd1);
        close(fd2);
        close(fd3);
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    image-20220815173321291

  • 相关阅读:
    雷军3小时演讲感受
    力扣大厂热门面试算法题 21-23
    pytorch安装教程
    word中给公式加序号的方法
    web前端-javascript-逻辑运算符(! 非取反,短路的&& 与,短路的|| 或,&& || 非布尔值的情况,对于非布尔值进行与或运算时,会先将其转换为布尔值,然后再运算,并且返回)
    如何判断一个程序是 32bit 还是 64bit ?
    vue echarts 镂空饼图配置
    白炽灯和节能灯哪个更护眼?分享几款护眼的LED灯
    如何精准识别主数据?
    SSM - Springboot - MyBatis-Plus 全栈体系(二十三)
  • 原文地址:https://blog.csdn.net/qq_41474648/article/details/126426110