0
点赞
收藏
分享

微信扫一扫

基于SpringBoot的点餐系统的设计与实现(源码+数据库+文档+说明)

快乐码农Alan007 2023-06-29 阅读 41

前文

一,什么是命名管道?

 二,命名管道的基本原理

三,创建命名管道实现两个进程对写

 四,匿名管道和命名管道的区别

总结


前文

一,什么是命名管道?

 

int mkfifo(const char *path,mode_t mode);
int main(int argc, char *argv[])
{
 mkfifo("./fifo", 0644);
 return 0;
}

 二,命名管道的基本原理

 

三,创建命名管道实现两个进程对写

写端

#include <iostream>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string>
#include <assert.h>

using namespace std;

int main()
{
    //写方创造管道文件

    int n=mkfifo("./fifo",0666);
    if(n!=0)//创建失败
    {
        cout<<errno<<":"<<strerror(errno)<<endl;
        return 1;
    }

    //以写的方式打开文件
    int fd=open("./fifo",O_WRONLY);
    assert(fd>=0);

    //写入内容
    while(true)
    {
        char buffer[1024];

        char* ret=fgets(buffer,sizeof(buffer)-1,stdin);//从屏幕读取内容

        //写入管道
        size_t size=write(fd,buffer,strlen(buffer));
        assert(size>=0);//判断是否成功写入

    }

    //关闭文件
    close(fd);
    return 0;
}

读端

#include <iostream>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
using namespace std;

int main()
{
    //直接以读的方式打开
    int fd=open("./fifo",O_RDONLY);
    assert(fd>=0);

    //读取内容
    while(true)
    {
        char buffer[1024];

        size_t size=read(fd,buffer,sizeof(buffer)-1);
        if(size>0)//读取有内容,打印内容
        {
            cout<<buffer<<endl;
        }
        else if(size=0)//读取数为0,说明写端不再写入,读端退出
        {
            cout<<"写端停止写入,读端退出"<<endl;
            break;
        }
        else//读取异常退出
        {
            cout<<"读取异常"<<endl;
            break;
        }
    }

    //关闭
    close(fd);
    return 0;
}

 运行效果

 四,匿名管道和命名管道的区别

总结

举报

相关推荐

0 条评论