zoukankan      html  css  js  c++  java
  • dup与dup2函数

    1. 依赖的头文件

      #include <unistd.h>
      
    2. 函数定义

      int dup(int oldfd);
      int dup2(int oldfd, int newfd);
      
    3. 函数作用

      • dup和dup2都可用来复制一个现存的文件描述符,使两个文件描述符指向同一个file结构体。
      • 如果两个文件描述符指向同一个file结构体,File Status Flag和读写位置只保存一份在file结构体中,并且file结构体的引用计数是2。
      • 如果两次open同一文件得到两个文件描述符,则每个描述符对应一个不同的file结构体,可以有不同的File Status Flag和读写位置。
    4. 实战

      • 需求:在代码中执行2次printf("hello Linux "),前一次输入到world文件中,后一次输入到屏幕上
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <stdio.h>
    
    void file_Redirect()
    {
        //先备份现场
        int outfd = dup(1);
        //先做重定向
        int fd = open("world", O_WRONLY|O_CREAT,0666);
        //标准输出到重定向fd到对应的文件
        dup2(fd, 1);
        printf("hello Linux
    ");
        //需要来一次刷新
        fflush(stdout);
        //需要恢复1,重新到标准输出
        dup2(outfd, 1);
        printf("hello Linux
    ");
    }
    int main(int argc, char* argv[])
    {
        file_Redirect();
        return 0;
    }
    
  • 相关阅读:
    Hadoop OutputFormat浅析
    硬盘性能
    HDFS读文件过程分析:读取文件的Block数据
    HDFS写文件过程分析
    JAVA中的编码分析
    HBase 写入优化
    HBase ttl 验证
    大数据多维分析平台的实践
    TiDB在特来电的探索
    Druid 基础使用-操作篇(Pivot、plyql)
  • 原文地址:https://www.cnblogs.com/LittleFishC/p/12530820.html
Copyright © 2011-2022 走看看