zoukankan      html  css  js  c++  java
  • linux知识复习1-dup dup2

     1 #include <sys/stat.h>
     2 #include <string.h>
     3 #include <fcntl.h>
     4 #include <stdio.h>
     5 #include <unistd.h>
     6 int main(void)
     7 {
     8     #define STDOUT 1 
     9     int nul, oldstdout;
    10     char msg[] = "This is a test";
    11     /* create a file */
    12     nul = open("DUMMY.FIL", O_CREAT | O_RDWR, S_IREAD | S_IWRITE);
    13     /* create a duplicate handle for standard
    14     output */
    15 
    16     oldstdout = dup(STDOUT); //复制用于后续恢复
    17     /*
    18     redirect standard output to DUMMY.FIL
    19     by duplicating the file handle onto the
    20     file handle for standard output.
    21     */
    22     dup2(nul, STDOUT); //将标准输出重定向到nul
    23     /* close the handle for DUMMY.FIL */
    24     close(nul);
    25     /* will be redirected into DUMMY.FIL */
    26     write(STDOUT, msg, strlen(msg));
    27     /* restore original standard output
    28     handle */
    29     dup2(oldstdout, STDOUT); //将标准输出重定向到之前保存的标准输出
    30     /* close duplicate handle for STDOUT */
    31     close(oldstdout);
    32     return 0;
    33 }

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

    进程fd表 ---- 文件表----v节点表

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

    指向关系改变:

    dup2(nul, STDOUT)

    STDOUT指向了nul的文件表;

    dup2(oldstdout, STDOUT)

    STDOUT指向了oldstdout保存的文件表;

    打开文件的每个进程都有独立的文件表项,可以使每个进程都有自己对于该文件的当前偏移;

    详细参考:

    http://www.cnblogs.com/GODYCA/archive/2013/01/05/2846197.html

  • 相关阅读:
    CAP 理论笔记
    介绍 GOMEZ
    CDN资料下载(1) 20091223
    About网宿CDN
    [笔记] Darwin Streaming server 的 Task 类
    手把手教你写“隐藏图标托盘程序”
    WIN7下使用OpenSCManger和OpenService函数的注意
    oracle按月、日、时分组查询数据,为空的数据补零
    搜索引擎学习
    JSONP与JSON
  • 原文地址:https://www.cnblogs.com/wanpengcoder/p/4186906.html
Copyright © 2011-2022 走看看