Chinaunix首页 | 论坛 | 博客
  • 博客访问: 411326
  • 博文数量: 48
  • 博客积分: 1032
  • 博客等级: 上士
  • 技术积分: 1256
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-19 13:24
文章分类

全部博文(48)

文章存档

2014年(3)

2013年(23)

2012年(22)

分类: LINUX

2012-10-20 19:38:18

    管道:单向、先进先出,将一个进程的输出和另一个进程的输入连接在一起。从管道尾部写入数据,头部读出数据。通称所说的管道是无名管道;有名管道称作为FIFO;数据被一个进程读出后,将被从管道中删除,其它读进程将不能再读到这些数据。管道提供了简单的流控制机制,进程试图读空管道时,进程将阻塞。当然,管道已经满了,进程再试图向管道中写入数据,进程将阻塞。

分类:无名管道和有名管道,前者用于父子进程之间的通信,后者用于同一系统下的任意两个进程间的通信(如同读写文件一样)。

无名管道:由pipe()函数创建
int pipe(int filedis[2]);   成功返回 0 ;  失败返回 -1;

参数说明:filedis[2]是一个整形数组,存放由pipe()函数返回的两个文件描述符。
filedis[0]:用于读管道;  
filedis[1]:用于写管道;

关闭管道:需要关闭两个文件描述,用close()函数即可;close(filedis[0]);

通常先创建一个管道,在用fork()函数创建一个子进程,该子进程会继承父进程所创建的管道。必须在系统调用fork()之前调用pipe(),否则子进程将不会继承文件描述符。

参考程序:

点击(此处)折叠或打开

  1. #include <unistd.h>
  2. #include <sys/types.h>
  3. #include <errno.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>

  6. int main()
  7. {
  8.     int pipe_fd[2];
  9.     pid_t pid;
  10.     char buf_r[100];
  11.     char* p_wbuf;
  12.     int r_num;
  13.     
  14.     memset(buf_r,0,sizeof(buf_r));
  15.     
  16.     /*创建管道*/
  17.     if(pipe(pipe_fd)<0)
  18.     {
  19.         printf("pipe create error\n");
  20.         return -1;
  21.     }
  22.     
  23.     /*创建子进程*/
  24.     if((pid=fork())==0) //子进程 OR 父进程?
  25.     {
  26.         printf("\n");
  27.         close(pipe_fd[1]);
  28.         sleep(2); /*为什么要睡眠*/
  29.         if((r_num=read(pipe_fd[0],buf_r,100))>0)
  30.         {
  31.             printf( "%d numbers read from the pipe is %s\n",r_num,buf_r);
  32.         }    
  33.         close(pipe_fd[0]);
  34.         exit(0);
  35.       }
  36.     else if(pid>0)
  37.     {
  38.         close(pipe_fd[0]);
  39.         if(write(pipe_fd[1],"Hello",5)!=-1)
  40.             printf("parent write1 Hello!\n");
  41.         if(write(pipe_fd[1]," Pipe",5)!=-1)
  42.             printf("parent write2 Pipe!\n");
  43.         close(pipe_fd[1]);
  44.         sleep(3);
  45.         waitpid(pid,NULL,0); /*等待子进程结束*/
  46.         exit(0);
  47.     }
  48.     return 0;
  49. }

阅读(1539) | 评论(0) | 转发(0) |
0

上一篇:IPC---信号量

下一篇:IPC---TCP套接字通信

给主人留下些什么吧!~~