Hello! 欢迎来到小浪云!


【Linux】进程间通信:命名管道


命名管道是一种用于进程间通信的机制,能够在没有亲缘关系的进程之间进行数据交换。它们被称为命名管道,因为它们通过文件系统中的一个特殊文件来实现通信,尽管这个文件实际上并不存储数据,而是维护一个内存中的缓冲区,执行先进先出的数据传输。

要在文件系统中创建一个命名管道,可以使用mkfifo()或mknod()函数。创建后,一个进程可以以写入模式打开该管道并向其中写入数据,而另一个进程则可以以读取模式打开该管道并从中读取数据。数据在命名管道中的流动是单向的。

【Linux】进程间通信:命名管道

命令行创建命名管道可以使用以下命令:

mkfifo filename

【Linux】进程间通信:命名管道 以p开头的文件表示它是一个管道文件。

【Linux】进程间通信:命名管道【Linux】进程间通信:命名管道 命名管道的读写操作是阻塞的,且管道文件的大小始终为0,因为数据存储在内存中。

命名管道也可以通过编程方式创建,使用以下函数:

int mkfifo(const char *filename, mode_t mode);

为了管理命名管道的生命周期,可以创建一个namedPipe.hpp文件,提供管道创建和关闭的函数:

#pragma once #include<iostream> #include <sys> #include <sys> #include<String> #include<cerrno> #include<cstdio> #include<unistd.h> using namespace std; <p>const string comm_path ="./myfifo";</p><p>int CreateNamedPipe(const string & path) { int res =mkfifo(path.c_str(),0666); if(res!=0) { perror("mkfifo"); } return res; }</p><p>int RemoveNamedPipe(const string & path) { int res =unlink(path.c_str()); if(res!=0) { perror("unlink"); } return res; } </unistd.h></cstdio></cerrno></string></sys></sys></iostream>

在server.cc中,可以使用这些函数来创建和删除命名管道:

#include"namedPipe.hpp"</p><p>int main() { CreateNamedPipe(comm_path); RemoveNamedPipe(comm_path); return 0; }

为了简化操作,可以将这些功能封装在一个类中:

class NamedPipe { public: NamedPipe(const string &path) : _fifo_path(path) { int res = mkfifo(path.c_str(), 0666); if (res != 0) { perror("mkfifo"); } } ~NamedPipe() { int res = unlink(_fifo_path.c_str()); if (res != 0) { perror("unlink"); } } private: const string _fifo_path; };

这样,主函数中只需创建一个NamedPipe对象即可:

NamedPipe myfifo(comm_path);

管道会在对象销毁时自动释放。

进一步地,可以在类中添加其他功能,如打开管道、读取和写入数据:

const string comm_path = "./myfifo";</p><h1>define DefaultFd -1</h1><h1>define Creater 1</h1><h1>define User 2</h1><h1>define Read O_RDONLY</h1><h1>define Write O_WRONLY</h1><p>class NamedPipe { private: bool OpenNamedPipe(int mode) { _fd = open(_fifo_path.c_str(), mode); if (_fd 

隐藏打开文件的函数操作,并定义宏常量Read和Write来指定打开文件的方式。初始化时传递执行者身份(创建者还是使用者),以决定是否需要再次创建管道文件。

int ReadNamedPipe(string <em> out)//输出型参数,输入型const& 输入输出型& { char buffer[BaseSize]; int n = read(_fd,buffer,sizeof(buffer)); if(n>0) { buffer[n]=0; </em>out = buffer; }</p><pre class="brush:php;toolbar:false">return n;

} int WriteNamedPipe(const string & in) { write(_fd,in.c_str(),in.size()); }

【Linux】进程间通信:命名管道【Linux】进程间通信:命名管道【Linux】进程间通信:命名管道

相关阅读