住宅城乡建设部门户网站,seo主管的seo优化方案,wordpress插件audio player,网址搜索栏在哪文章目录 前言一、命名管道接口函数介绍二、使用步骤 前言
上章内容#xff0c;我们介绍与使用了管道。上章内容所讲的#xff0c;是通过pipe接口函数让操作系统给我们申请匿名管道进行进程间通信。 并且这种进程间通信一般只适用于父子进程之间#xff0c;那么对于两个没有… 文章目录 前言一、命名管道接口函数介绍二、使用步骤 前言
上章内容我们介绍与使用了管道。上章内容所讲的是通过pipe接口函数让操作系统给我们申请匿名管道进行进程间通信。 并且这种进程间通信一般只适用于父子进程之间那么对于两个没有“血缘”关系的进程我们还能通过怎样的方式来进行通信呢
本章内容主要讲解命名管道的通信而命名管道顾名思义既然匿名管道是没有名字的管道那么命名管道就是有名字的管道。 一、命名管道接口函数介绍 先来讲讲函数名mk - make fifo - first in first out先进先出因为管道的buffer就是先进先出的策略所以函数名为mkfifo。 第一个参数 const char* pathname: 这个参数是作为你要生成的命名管道的路径与名字。不过要注意的是这个文件的路径最好是你有权限去进行访问不然可能会出现各种问题。 第二个参数 mode_t mode 因为既然你要生成一个命名管道文件那么你就需要给它制定文件的访问权限。 二、使用步骤
使用步骤与匿名管道比较相似只是多了需要自己调用mkfifo函数的过程
// # fifo.hpp
#ifndef _FIFO_COM
#define _FIFO_COM#includeiostream
#includecstdio
#includeassert.h
#includesys/types.h
#includesys/stat.h
#includeunistd.h
#includefcntl.h
#includecstdio
#includestring.h
#includestring#define PATH_NAME ./fifo.ipc
std::string END_STR(end);
#endif
// Server端
#include fifo.hpp
#include Log.hppint main()
{// 1.申请命名管道int ret mkfifo(PATH_NAME, 0666);if (ret -1){perror(mkfifo);exit(1);}int a 0;Log(Debug) Server: make named_pipe success! Step1 std::endl;// 2.打开命名管道文件// Server端进行写操作int fd open(PATH_NAME, O_WRONLY);if (fd -1){perror(open);exit(2);}Log(Debug) Server: open named_pipe success! Step2 std::endl;// 3.开始写std::string buffer;while (1){std::cout Please Enter Message Line ,End enter end : ;std::getline(std::cin, buffer);if(buffer END_STR) break;write(fd, buffer.c_str(), buffer.size());}//.关闭命名管道close(fd);Log(Debug) Server: close fc done! Step3 std::endl;return 0;
}// Client端
#include fifo.hpp
#include Log.hpp
int main()
{// 1.打开命名管道文件// Client端进行读int fd open(PATH_NAME, O_RDONLY);if (fd -1){perror(open);exit(2);}char buffer[1024];Log(Debug) Client: open named_pipe success! Step1 std::endl;// sleep(5);// 开始进行读while (1){memset(buffer, \0, sizeof(buffer));int n read(fd, buffer, sizeof(buffer) - 1);if (n 0){// 读到了文件末尾Log(Debug) Read done! std::endl;break;}else if (n 0){std::cout Server say: buffer std::endl;}}close(fd);unlink(PATH_NAME);Log(Debug) Client: close named_pipe success! Step2 std::endl;Log(Debug) Client: close fd done! Step3 std::endl;return 0;
}// Log.hpp 日志
#include iostream
#include time.h
#include string#define Debug 0
#define Error 1const std::string com[] {Debug,Error};std::ostream Log(int command)
{std::cout [ (unsigned)time(nullptr) ]: [ com[command] ] ;return std::cout;
}需要特别注意的是对于管道文件必须读写两端都打开管道文件也就是都进行open管道文件否则读端或者写端就会被堵塞在open函数。