linux进程通信--无名管道

 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向管道中写字符就可以了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值