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

#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

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章