kunyashaw博客主页 关注kunyashaw新博客 关于kunyashaw 转到底部

linux——ipc in pipe

1、概念

管道:pipe,又称无名管道,是一种特殊类型的文件,在应用层体现为两个打开的文件描述符。

它和有名管道、信号都是unix进程间通信方式。

2、用途

主要用于父进程与子进程之间,或者两个兄弟进程之间。

3、特点

7个,

①半双工。

数据在同一时候只能在同一个方向流动(举例:对讲机。全双工:手机,单工:遥控器)

②只存在于内存当中。

不是个普通的文件,不属于于文件系统(与普通文件的区别:无法通过open、close、read、write来操作管道文件,只能通过继承来获取文件描述符)

③没有名字。

只能在具有公共祖先的进程之间使用

④缓冲区大小固定。

linux中,管道的缓冲区大小事4kb。

⑤传输的数据时无格式的。

故要求读写双方约定数据格式、大小

⑥数据只能从管道一端读,一端写。

⑦读数据为一次性操作,一旦读走,数据被抛弃,释放空间。

4、使用方法

#include <unistd.h>
 int pipe(int fd[2]);
 功能:经由参数fd返回两个文件描述符
 参数:
fd为int型数组的首地址,其存放了管道的文件描述符fd[0]、fd[1]。
fd[0]为读而打开,fd[1]为写而打开管道
 返回值:
 成功:返回 0
 失败:返回-1

5、举例

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
 int fd_pipe[2];
 char buf[] = "hello world";
 pid_t pid;
 
 if (pipe(fd_pipe) < 0)
    perror("pipe");
 pid = fork();
 if (pid < 0)
 {
  perror("fork");
  exit(-1);
 }
 if (pid == 0)
 {
  write(fd_pipe[1], buf, strlen(buf));
  _exit(0);
 }
 else
 {
  wait(NULL);
  memset(buf, 0, sizeof(buf));
  read(fd_pipe[0], buf, sizeof(buf));
  printf("buf=[%s]\n", buf);
 }
 return 0;
}

posted @ 2013-06-05 11:53  kunyashaw  阅读(181)  评论(0编辑  收藏  举报
回到顶部