zoukankan      html  css  js  c++  java
  • Linux_C 输入输出重定向

    将stdin定向到文件有3种方法:

    1.close then open .类似挂断电话释放一条线路,然后再将电话拎起来从而得到另一条线路。

        先close(0);将标准输入关掉,那么文件描述符数组中的第一个元素处于空闲状态。(一般数组0=stdin, 1=stdout, 2=stderror,如果不关闭那么进程请求一个新的文件描述符的时候系统内核将最低可用的文件描述符给它,那么就是2以后的元素,关掉0,就分配了0给新进程)。

    close(0);  fd=open("/etc/passwd", O_RDONLY);

    2.open..close..dup..close

     先fd=open(file),打开stdin要重定向的文件,返回一文件描述符,不过它不是0,因为0还在当前被打开了。

       close(0)关闭0

       dup(fd),复制文件描述符fd,此次复制使用最低可用文件描述符号。因此获得的是0.于是磁盘文件和0连接一起了。

      close(fd).

    3.open..dup2..close.

    下面说说dup的函数

    dup   dup2

    #include <fcntl.h>

    newfd = dup(oldfd);

    newfd = dup2(oldfd, newfd);  oldfd需要复制的文件描述符,newfd复制oldfd后得到的文件描述符

    return    -1:error   newfd:right

     1 /* whotofile.c
     2  * purpose: show how to redirect output for another program 
     3  *    idea: fork, then in the child , redirect output , then exec
     4  */
     5 #include <stdio.h>
     6 #include <fcntl.h>
     7 int main(void) {
     8   int pid, fd;
     9   printf("About to run the who.
    ");
    10   if((pid=fork()) ==-1){
    11     perror("fork");
    12     exit(1);
    13   }
    14   if(pid==0) {
    15     //    close(1);
    16     fd = creat("userlist", 0644);
    17     close(1);
    18     dup2(fd, 1);
    19     execlp("who", "who", NULL);
    20     perror("execlp");
    21     exit(1);
    22   }
    23   if(pid!=0) {
    24     wait(0);
    25     printf("Done running who. results in userlist.
    ");
    26   }
    27   return 0;
    28 }

    内核总是使用最低可用文件描述符;

    文件描述符集合通过exec调用传递,而且不会被改变。

  • 相关阅读:
    搜索专题: HDU1242 Rescue
    搜索专题: HDU2102 A计划
    搜索 问题 D: 神奇密码锁
    HNUSTOJ-1674 水果消除(搜索或并查集)
    搜索专题:问题 E: 挑战ACM迷宫
    【网络流24题】【洛谷P4013】数字梯形问题【费用流】
    【网络流24题】【洛谷P4013】数字梯形问题【费用流】
    【牛客想开了大赛2 B】n的约数【打表】
    【牛客想开了大赛2 B】n的约数【打表】
    【牛客想开了大赛2 A】平面【数论,数学】
  • 原文地址:https://www.cnblogs.com/wizzhangquan/p/4075115.html
Copyright © 2011-2022 走看看