zoukankan      html  css  js  c++  java
  • dup2()函数的使用,

    #define STR "xiamanman "
    #define STR_LEN 10
    #define STDOUT 1

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


    int main()
    {
      int fd = open("./temp", O_CREAT|O_RDWR|O_APPEND);

      int s_fd = dup(STDOUT);

      dup2(fd, STDOUT);

      close(fd);

      write(STDOUT, STR, STR_LEN);

      dup2(s_fd, STDOUT);

      close(s_fd);

      write(STDOUT, STR, STR_LEN);

      printf("xx ");

      return 0;
    }

    --------------------------------------------------------------------

    参考资料,dup2 百度百科。主要参考英文的代码。

    #define STDOUT 1

    int main(void)
    {

      int nul,oldstdout;
      char msg[] = "This is a test";


      /* create a file */
      nul = open("DUMMY.FIL",O_CREAT | O_RDWR |
            S_IREAD | S_IWRITE);


      /* create a duplicate handle for standard
      output */

      oldstdout = dup(STDOUT);


      /*
      redirect standard output to DUMMY.FIL
      by duplicating the file handle onto the
      file handle for standard output.
      */
      dup2(nul,STDOUT);


      /* close the handle for DUMMY.FIL */
      close(nul);


      /* will be redirected into DUMMY.FIL */
      write(STDOUT,msg,strlen(msg));


      /* restore original standard output
      handle */
      dup2(oldstdout,STDOUT);


      /* close duplicate handle for STDOUT */
      close(oldstdout);


      return 0;
    }

  • 相关阅读:
    BZOJ3997:[TJOI2015]组合数学(DP,Dilworth定理)
    BZOJ4807:車(组合数学,高精度)
    BZOJ4008:[HNOI2015]亚瑟王(DP,概率期望)
    BZOJ1499:[NOI2005]瑰丽华尔兹(DP,单调队列)
    洛谷1514 引水入城
    洛谷 1018 乘积最大
    八数码难题
    CODEVS 1069关押罪犯
    CODEVS 1067 机器翻译
    洛谷 P1417 烹调方案
  • 原文地址:https://www.cnblogs.com/zhangxuan/p/5970633.html
Copyright © 2011-2022 走看看