• 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

  • 相关阅读:
    每天记录学习的新知识:AppInit
    pytorch JIT
    java时间格式化
    element el-table 设置fixed导致行错乱问题
    20220720学习反思
    【3D图像分割】基于Pytorch的 VNet 3D 图像分割4(改写数据流篇)
    GBASE 8C——SQL参考6 sql语法(4)
    vlang捣鼓之路
    web前端大作业:诗人文化网页主题网站【唐代诗人】纯HTML+CSS制作
    AI在日常生活中有哪些应用?
  • 原文地址:https://blog.csdn.net/qq_41474648/article/details/126426110