Linux 管道通信 .

来源:互联网 发布:js数组remove和push 编辑:程序博客网 时间:2024/06/04 18:06
一、定义

  管道是单向的、先进先出的。它将一个程序的输入和另一个程序的输出连接起来。数据被一个进程读出后,将被从管道中删除。分为无名和有名管道两种。前者用于父进程和子进程间的通信,后者用于同一系统的两个进程间通信。

 

二、无名管道

     int  pipe(int fd[2]);

   其中,fd[0]用于读管道,fd[1]用于写管道。若成功则返回零,否则返回-1,错误原因存于errno中。

三、有名管道:FIFO

     int mkfifo(const char* pathname,mode_t mode)

open时使用O_NONBLOCK,访问要求无法满足则立即出错返回。erron是ENXIO。

 

        例子:

[cpp] view plaincopyprint?
  1. fread.c                          //读文件  
  2.   
  3. #include<errno.h>   
  4. #include<memory.h>   
  5. #define FIFO "myfifo"           
  6. main(){  
  7.         int fd;  
  8.         char buff[100];  
  9.         if(access(FIFO,F_OK) == -1){  
  10.                 mkfifo(FIFO,0777);       
  11.         }  
  12.         fd=open(FIFO,O_RDONLY|O_NONBLOCK);    //设置非阻塞打开,否则当没有输入时,会阻塞在read函数         
  13.   
  14.         int num;  
  15.         while(1){  
  16.                 memset(buff,'\0',100);             //如不清空最后的字符会出现乱码  
  17.                 if((num=read(fd,buff,100))==0){  
  18.                         printf("waiting.....\n");  
  19.                         sleep(1);  
  20.                         continue;  
  21.                 }  
  22.                 printf("read %d in fifo , it's %s",num,buff);  
  23.                 sleep(1);  
  24.         }  
  25. }  
  26.   
  27.   
  28. fwrite.c                //写文件   
  29.   
  30.    
  31.   
  32. #include<stdio.h>   
  33. #include<fcntl.h>   
  34. #include<memory.h>   
  35. #define FIFO "myfifo"   
  36. main(){  
  37.         int fd;  
  38.         char buff[100];  
  39.         memset(buff,'\0',100);  
  40.         scanf("%s",buff);  
  41.         if(access(FIFO,F_OK) == -1){  
  42.                 mkfifo(FIFO,0777);  
  43.         }  
  44.         fd=open(FIFO,O_WRONLY);  
  45.         int num;  
  46.         num=write(fd,buff,strlen(buff));  
  47.         printf("%d char is written! It's %s\n",num,buff);  
  48. }  


 

 

4、管道关闭:用close()关闭相应的文件描述符即可。