Chinaunix首页 | 论坛 | 博客
  • 博客访问: 101042
  • 博文数量: 8
  • 博客积分: 467
  • 博客等级: 一等列兵
  • 技术积分: 80
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-22 22:16
个人简介

追梦人

文章分类
文章存档

2013年(1)

2012年(1)

2011年(2)

2010年(4)

分类:

2011-05-01 13:01:40

无名管道

管道是UNIX系统IPC的最古老形式,所有的UNIX系统都支持这种通信机制。有两个局限性:

(1)       支持半双工;

(2)       只有具有亲缘关系的进程之间才能使用这种无名管道;

pipe函数

功能:创建无名管道

函数原型:#include

          int pipe(int filedes[2]);

参数经由参数filedes返回两个文件描述符,filedes[0]为读而打开,filedes[1]为写而打开。

经典的管道使用模型

使用管道的注意事项:

1.       当读一个写端已经关闭的管道时,在所有数据被读取之后,read函数返回值为0,以指示到了文件结束处;

2.       如果写一个读端关闭的管道,则产生SIGPIPE信号。如果忽略该信号或者捕捉该信号并处理程序返回,则write返回-1errno设置为EPIPE

实例

   系统调用pipe创建一个管道,子进程想管道里面写

             Child process is sending a message

父进程从管道中读出,并显示

#include

#include

#define SIZE    128

int pid;

 

int main(int argc, char *argv[])

{

       int fd[2];

       char out[SIZE];

       char in[SIZE] = “Child process is sending a message”;

      

       pipe(fd);  // create a pipe

       while((pid = fork()) < 0);   //create a child process

       if(pid == 0)  //in child process

       {

              close(fd[1]);

              read(fd[0], out, SIZE);

              fprintf(stdout, “%s\n”, out);

              exit(0);

}

else   //in parent process

{

       close(fd[0]);

       write(fd[1], in, SIZE);

       sleep(2);

       exit(0);

}

       return 0;

}

阅读(6270) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~