zoukankan      html  css  js  c++  java
  • I/O -x dup() dup2()

    dupdup2函数:int dup(int filedes); int dup2(int filedes,int filedes2);

    返回:若成功为新的文件描述符,若出错为-1

    作用:用来复制一个文件描述符,经常用来重定向进程的stdin,stdout,stderr

    dup返回的新文件描述符一定是当前可用文件描述符中最小数值,该新的描述符是传递给它的描述符的拷贝,这意味着这两个描述符共享同一个数据结构。用dup2则可以用filedes2参数指定新描述符的数值,如果filedes2已经打开,则先将其关闭,如果filedes等于filedes2,则dup2返回filedes2,而不关闭它。

    范例:

     1 #include <stdio.h>
     2 
     3 #include <stdlib.h>
     4 
     5 #include <unistd.h>
     6 
     7 #include <sys/stat.h>
     8 
     9 #include <sys/types.h>
    10 
    11 #include <fcntl.h>
    12 
    13 int main(void)
    14 
    15 {
    16 
    17      int fd;
    18 
    19      int fddup;
    20 
    21      int fddup2;
    22 
    23      char buf1[]="Hello, world!";
    24 
    25      char buf2[50];
    26 
    27      if((fd=open("/home/sam/helloworld",O_CREAT|O_TRUNC|O_RDWR,0666))==-1)
    28 
    29      {
    30 
    31          printf("Open or create file named "helloworld" failed.
    ");
    32 
    33          exit(1);
    34 
    35      }
    36 
    37      printf("%d
    ",fd);
    38 
    39      write(fd,buf1,sizeof(buf1));
    40 
    41      close(fd);
    42 
    43  
    44 
    45      if((fd=open("/home/sam/helloworld",O_RDONLY))==-1)
    46 
    47      {
    48 
    49          printf("Open file named "helloworld" failed.
    ");
    50 
    51          exit(1);
    52 
    53      }
    54 
    55      printf("%d
    ",fd);
    56 
    57      fddup=dup(fd);
    58 
    59      fddup2=dup2(fd,8);
    60 
    61      printf("%d
    ",fddup);
    62 
    63      printf("%d
    ",fddup2);
    64 
    65  
    66 
    67      read(fddup2,buf2,sizeof(buf2));
    68 
    69      printf("%s
    ",buf2);
    70 
    71      close(fd);
    72 
    73      close(fddup);
    74 
    75      close(fddup2);
    76 
    77      return 0;
    78 
    79 }
  • 相关阅读:
    【整理】【代码的坏味道】过长函数(Long Method)
    【整理】【代码的坏味道】重复代码(Duplicated Code)
    【原创】Winform下拉框自动选择实现
    time及各种cpu时间
    arch安装及配置xfce4桌面
    paste工具
    十分有用的cut剪切命令
    ubuntu一些脚本的执行顺序
    Linux一些经典书籍
    强大的wget下载工具
  • 原文地址:https://www.cnblogs.com/pencil-zh/p/4508159.html
Copyright © 2011-2022 走看看