zoukankan      html  css  js  c++  java
  • Linux_C dup()

     1 /*
     2  * stdinredir2.c
     3  * shows two more methods for redirecting standard input
     4  * use #define to set one or the other
     5  */
     6 #include <stdio.h>
     7 #include <fcntl.h>
     8 /*#define CLOSE_DUP  /*open, close, dup, close */
     9 /*#define USE_DUP2   /*opne, dup2, close */
    10 int main(void) {
    11   int fd, newfd;
    12   char line[100];
    13   //read and print lines
    14   fgets(line, 100, stdin);
    15   printf("line: %s", line);
    16   
    17   fd=open("/home/wiz/wizcode/psh1.c", O_RDONLY);  /* open the disk file */
    18 
    19   #ifdef CLOSE_DUP
    20      close(0);
    21      newfd=dup(fd);              /*copy open fd to 0*/
    22   #else
    23      newfd=dup2(fd,0);           /*close 0, dup fd to 0*/
    24   #endif
    25   if(newfd!=0){
    26     fprintf(stderr, "Could not duplicate fd to 0
    ");
    27     exit(1);
    28   }
    29   close(fd);
    30   fgets(line, 100, stdin); printf("%s", line);
    31   fgets(line, 100, stdin); printf("%s", line);
    32   fgets(line, 100, stdin); printf("%s", line);
    33   return 0;
    34 }
  • 相关阅读:
    vue1.0
    网络抓包(四)
    物联网框架ServerSuperIO
    Solrcloud(Solr集群)
    机器学习1
    TCP/IP协议族(一)
    ElasticSearch(简称ES)
    工具
    线程本地变量的使用
    Features of Spring Web MVC
  • 原文地址:https://www.cnblogs.com/wizzhangquan/p/4074889.html
Copyright © 2011-2022 走看看