zoukankan      html  css  js  c++  java
  • 管道

      管道是 linux下支持的最初的IPC形式之一,管道是半双工的,数据只可以想一个方向流动;如果要双向流动的话,需要建立两个管道;

        一:无名管道:

          无名管道定是死的,pipe()函数返回的是一个二维数组类型,【0】端固定是读端,【1】端是写端;

          代码:

            

      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <signal.h>
      4 
      5 int main()
      6 {
      7     int fd[2];
      8     //
      9     int ret =pipe(fd);
     10     if(ret < 0)
     11     {
     12         perror("pipe!
    ");
     13         exit(EXIT_FAILURE);
     14     }
     15 
     16     int pid = fork();
     17     if(pid <0)
     18     {
     19         perror("fork!
    ");
     20         exit(EXIT_FAILURE);
     21     }
     22     if(pid ==0)
     23     {
     24         write(fd[1],"hello this child_process write!
    ",40);
     25     }
     26     if(pid >0)
     27     {
     28         sleep(3);
     29         char buff[40];
     30         read(fd[0],buff,40);
     31         printf("buff is %s
    ",buff);
     32     }
     33 
     34     return 0;
     35 
     36 
     37 }
     38 
     39 

      其中是,创建一个子进程,在子进程读,在父进程中来写;

    二.有名管道:

        

      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <signal.h>
      4 #include <fcntl.h>
      5   
      6 int main()
      7 { 
      8     //
      9     //int ret = mkfifo("myfifo",0644);
     10     //if(ret < 0)
     11     //{ 
     12     //  perror("pipe!
    ");
     13     //  exit(EXIT_FAILURE);
     14     //} 
     15  
     16     int fd=open("myfifo",O_RDWR);
     17     if(fd < 0)
     18     {
     19         perror("open!
    ");
     20         exit(EXIT_FAILURE);
     21     }   
     22             
     23     int ret=write(fd,"hello this is write!
    ",40);
     24     if(ret < 0)
     25     {   
     26         perror("write!
    ");
     27         exit(EXIT_FAILURE);
     28     }   
     29  
     30     char buff[40];
     31     ret=read(fd,buff,40);
     32     if(ret < 0)
     33     {       
     34         perror("open
    ");
     35         exit(EXIT_FAILURE);
     36     }
     37  
     38     printf("buff is %s
    ",buff);
     39     close(fd);
     40     return 0;
     41    
     42  
     43 }

      有名管道就是通过mkfifo开创建一个管道文件,对文件来读写操作;

      

  • 相关阅读:
    html <select> <option> 实现根据选择不同的option,调用不同的方法功能
    jquery 实现无缝循环广告
    Linux 一次性杀死用户所有进程
    jquerymobile总结
    jQuery lightBox plugin
    开始算法复习。。。
    关于android Intent意图的一点心得
    好了,咳咳,就从这里这时开始吧
    CSV文件的生成与分析
    【观点】想写代码?离开你的电脑吧!
  • 原文地址:https://www.cnblogs.com/hongzhunzhun/p/4570211.html
Copyright © 2011-2022 走看看