【进程间通信】有名管道实现进程间通信详解

无名管道类似于无名管道,一般都会和无名管道比较着来说

无名管道的创建

在这里插入图片描述

特点

  • 用于同一台PC机的两个进程,可以是亲缘进程,也可以是不相关的进程
  • 通过文件IO操作管道
  • 不支持lseek等跳转光标函数
  • 遵循先进先出的原则
  • 存在于文件系统中,可以看到。文件类型为p(管道文件)

读写操作

读操作

  • 如果之前fifo管道内没有数据,读进程就会一直阻塞,一直阻塞到有数据写入或FIFO管道写端关闭

写操作

  • 只要FIFO中有空间,数据就可以写入,若空间不足,写进程就会阻塞,直到数据全部写入

读端代码

/*************************************************************************
	> File Name: fifo_one.c
	> 功能:创建一个管道,此程序用来读出管道中的数据 
	> Mail: 
	> Created Time: Thu 15 Aug 2019 12:45:50 AM PDT
 ************************************************************************/

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

int main()
{
    int fifo=0;
    int fd=0;
    int ret=0;
    char buf[1024]={0};
//创建一个管道
   fifo= mkfifo("/home/linux/Desktop/myfifo",0666);
    if(fifo<0)
    {
        perror("mkfifo error");
        exit(-1);
    }
//以只读模式,打开一个管道
    fd=open("/home/linux/Desktop/myfifo",O_RDONLY);
    if(fd<0)
    {
        perror("open error");
        exit(-2);
    }
    while(1)
    {
        ret=read(fd,buf,sizeof(buf));
        if(ret<0)
        {
            perror("read error");
            exit(-3);
        }
        if(ret==0)
        {
            printf("这次什么也没有读到\n");
            exit(66);
        }
        printf("这次读到的东西是%s\n",buf);
        memset(buf,0,sizeof(buf));
    }
    close(fd);
    remove("/home/linux/Desktop/myfifo");
return 0;
}

写端代码

/*************************************************************************
	> File Name: fifo_two.c
	> Author: 
	> Mail: 
	> Created Time: Thu 15 Aug 2019 01:34:46 AM PDT
 ************************************************************************/

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

int main()
{
    int fd=0;
    int ret=0;
    char buf[1024]={0};

//以只写模式打开一个管道文件
    fd=open("/home/linux/Desktop/myfifo",O_WRONLY);
    if(fd<0)
    {
        perror("open error");
        exit(-1);
    }
    while(1)
    {
        gets(buf);
        write(fd,buf,sizeof(buf));
        memset(buf,0,sizeof(buf));
    }
return 0;
}

运行演示

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值