命名管道(FIFO)的实现

管道随进程
命名管道是一个设备文件,是存在于硬盘上的文件
用mkfifo()创建命名管道,可用于任何两个进程之间的通信


client.c(写端)
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>     
#define _PATH_ "/tmp/file.tmp"
#define _SIZE_ 100
int main()
{
    int ret=mkfifo(_PATH_,0666|S_IFIFO);   //create FIFO
    if(ret==-1)
    {
        perror("mkfifo");
        return 1;
    }
    int fd=open(_PATH_,O_WRONLY);  //open by the way of write
    if(fd<0)
    {
        printf("open error\n");
    }
    char buf[_SIZE_];
    memset(buf,'\0',strlen(buf)+1);
    while(1)
    {
        scanf("%s",buf);
        int ret=write(fd,buf,strlen(buf)+1);
        if(ret<0)
        {
            printf("write error!\n");
            break;
        }
        if(strncmp(buf,"quit",4)==0)
        {
            break;
        }
    }
    close(fd);
    return 0;
}


server.c(读端)
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#define _PATH_ "/tmp/file.tmp"
#define _SIZE_ 100
int main()
{
    int fd=open(_PATH_,O_RDONLY);
    if(fd<0)
    {
        printf("open file error\n");
        return 1;
    }
    char buf[_SIZE_];
    memset(buf,'\0',sizeof(buf));
    while(1)
    {
        int ret=read(fd,buf,sizeof(buf));
        if(ret<=0)  //error or read the end of file
        {
            printf("error or read the end of file\n");
            break;
        }
        printf("%s\n",buf);
        if(strncmp(buf,"quit",4)==0)
        {
            break;
        }
    }
    close(fd);
    return 0;
}


结果:

wKioL1cTSGeQ2-o7AAAiihA6GWo898.png

本文出自 “追寻内心的声音” 博客,请务必保留此出处http://ljy789.blog.51cto.com/10697684/1764766

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值