Linux下C编程,进程通信之无名管道通信

最近在看进程间的通信,下面说说管道通信之无名管道。

1.概述

  管道是Linux中很重要的一种通信方式,他是把一个程序的输出直接连接到另一个程序的输入,并且管道具有队列的特性。如Linux命令,“ps -ef | grep root”。如下图所示:

2.无名管道

  2.1特点

  (1)它只能用于具有亲缘关系的进程之间的通信(也就是父子进程或者兄弟进程之间)。
  (2)它是一个半双工的通信模式,具有固定的读端和写端。
  (3)管道也可以看成是一种特殊的文件,对于它的读写也可以使用普通的read、write等函数。但是它不是普通的文件,并不属于其他任何文件系统,并且只存在于内存中。

  2.2主要函数说明

  int pipe(int fd[2])

    传入参数fd[2]数组,管道的两个文件描述符,之后就可以直接操作这两个文件描述符。其中fd[0]是“读”描述符,fd[1]是“写”描述符。

  2.3使用代码及说明

#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int pipe_fd[2];  /*用于保存两个文件描述符*/
    pid_t pid;
    char buf_r[100];  /*用于读数据的缓存*/
int r_num;  /*用于保存读入数据大数量*/ memset(buf_r,0,sizeof(buf_r)); if(pipe(pipe_fd)<0) /*创建管道,成功返回0,否则返回-1*/ return -1; /*fork()创建一子进程,
   具体使用可以参见:http://www.cnblogs.com/xudong-bupt/archive/2013/03/26/2982029.html
*/
if((pid=fork())==0) { close(pipe_fd[1]); /*关闭子进程写描述符,并通过使父进程暂停 2 秒确保父进程已关闭相应的读描述符*/ sleep(2); if((r_num=read(pipe_fd[0],buf_r,100))>0) /*子进程读取管道内容*/ printf("%d numbers read from the pipe is %s\n",r_num,buf_r); close(pipe_fd[0]);/*关闭子进程读描述符*/ exit(0); } else if(pid>0) { close(pipe_fd[0]);/*/关闭父进程读描述符,并分两次向管道中写入 Hello Pipe*/ if(write(pipe_fd[1],"Hello",5)!= -1) printf("parent write1 success!\n"); if(write(pipe_fd[1]," Pipe",5)!= -1) printf("parent write2 success!\n"); close(pipe_fd[1]);/*关闭父进程写描述符*/ sleep(3); exit(0); } }

 

posted on 2013-03-28 22:11  旭东的博客  阅读(2685)  评论(0编辑  收藏  举报

导航