• Linux_C 进程间共享管道


    程序pipe, 它使用可例如: ./pipe who sort   ./pipe ls head

     1 /* pipe.c
     2  * Demostrates how to create a pipeline from one process to another
     3  * * take two args, each a command ,and connects
     4  *   argv[1]s output to intput of argv[2]
     5  *   effect: command1 | command2
     6  */
     7 #include <stdio.h>
     8 #include <unistd.h>
     9 
    10 #define oops(x,n) { perror(x); exit(n); }
    11 
    12 int main(int argc, char *argv[]){
    13   int pid, thepipe[2];
    14   if(argc!=3) {
    15     fprintf(stderr, "usage: pipe cmd1 cmd2.
    ");
    16     exit(1);
    17   }
    18   if(pipe(thepipe) == -1)
    19     oops("pipe", 2);
    20   if((pid=fork()) == -1)
    21     oops("fork", 3);
    22   if(pid==0) {                  /*child execs argv[1] and writes into pipe*/
    23     close(thepipe[0]);          /*      child doesnt read from pipe       */
    24     if((dup2(thepipe[1], 1)) == -1)     /*child change the stdout, set the stdout into the pipe*/
    25       oops(argv[1], 6);
    26     close(thepipe[1]);          /*stdout is duped , close pipe*/
    27     execlp(argv[1], argv[1], NULL);
    28     oops("child", 4);
    29   }else if(pid>0) {             /*parent execs argv[0] and read from pipe*/
    30     close(thepipe[1]);          /*     parent doesnt write to pipe       */
    31     if(dup2(thepipe[0], 0) == -1)
    32       oops("could not redirect stdin", 6);
    33     close(thepipe[0]);          /*     stdin is duped, close pipe        */
    34     execlp(argv[2],argv[2], NULL);
    35     oops(argv[2], 5);
    36   }
    37   return 0;
    38 }
  • 相关阅读:
    xshell入门及Linux常用命令
    C++之vector
    c++ 之 string
    引用 与 指针
    关于时间复杂度的计算以及相关概念
    位运算
    thymeleafDemo
    面试总结
    关于mvvm原理实现,模拟vue(3)-----发布订阅
    关于mvvm原理实现,模拟vue(2)-----模板编译
  • 原文地址:https://www.cnblogs.com/wizzhangquan/p/4080119.html
Copyright © 2020-2023  润新知