linux进程通信--无名管道

来源:互联网 发布:软件项目管理 pdf下载 编辑:程序博客网 时间:2024/04/30 07:12
 linux无名管道通信特点
  1. 无名管道是半双工的通信方式,数据只能一方发送,另一方接收。
  2. 无名管道只适用于亲缘关系的进程通信。
  3. 数据的读出和写入:一个进程向管道中写的内容被管道另一端的进程读出。写入的内容每次都添加在管道缓冲区的末尾,并且每次都是从缓冲区的头部读出数据。
#include <stdio.h>#include <stdlib.h>#include <unistd.h>void read_data(int *);void write_data(int *);int main()      //主函数{           int pipefd[2];//无名管道指定pipefd[0]为读   pipefd[1]为写           pid_t cpid;           char buf;           if (pipe(pipefd) == -1)                {                   perror("pipe");                   exit(1);              }             cpid=fork();             switch(cpid)            {                 case -1:                     perror("creat proess failed");                 exit(1);   //此处执行的是退出子进程  而不是用break退出循环                 case 0:                    read_data(pipefd);                 default:                    write_data(pipefd);             }            return 0;}void read_data(int pipes[]){    int c,rc;    close(pipes[1]);    while(rc=read(pipes[0],&c,1)>0)    {        putchar(c);    }    exit(0);}void write_data(int pipes[]){    int c,rc;    close(pipes[0]);//关闭管道读    while((c=getchar())>0)    {        rc=write(pipes[1],&c,1);        if(rc<0)        {            perror("write file error");            close(pipes[1]);            exit(1);        }    }    close(pipes[1]);    exit(0);}
  • 主函数说明:主函数中使用pipe()函数创建无名管道,此时返回值为二维句柄,存入pipefd[2]中,其中pipefd[0]为无名管道读句柄,pipefd[1]为无名管道写句柄
  • 读函数:首先关闭写,再使用系统函数read从管道中读取字符就可以了
  • 写函数:首先关闭读,再使用系统函数write向管道中写字符就可以了
0 0