[轉] linux 經典的例子解釋dup dup2 文件描述符重定向函數輸入輸出重定向

出處:http://blog.csdn.net/eqxu/article/details/1641842

#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>
int main(void)
{
   #define STDOUT 1 //標準輸出文件描述符號
   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 */
//創建STDOUT的描述符備份
   oldstdout = dup(STDOUT);
   /*
      redirect standard output to DUMMY.FIL
      by duplicating the file handle onto the
      file handle for standard output.
   */
//重定向nul到STDOUT
   dup2(nul, STDOUT);
   /* close the handle for DUMMY.FIL */
//重定向之後要關閉nul
   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;
}
//結果就是msg寫到了文件中而不是STDOUT
未經允許不得轉載:GoMCU » [轉] linux 經典的例子解釋dup dup2 文件描述符重定向函數輸入輸出重定向