创建:
mkfifo 管道名删除:
rm -rf 管道名或者:
unlink 管道名创建:
声明如下:
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);open 函数中的权限参数。销毁:
#include <unistd.h>
int unlink(const char *pathname);errno以指示具体的错误类型。示例:
mkfifo("./filename",0666);//创建
unlink("./filename");//销毁当创建好管道后,进程通信就是简单的文件读写,如下:
把文件server.cc生成的程序作为读端。
#include<iostream>
#include<sys/types.h>
#include<sys/stat.h>
#include<cstdio>
#include<fcntl.h>
#include<unistd.h>
using namespace std;
int main()
{
int f = mkfifo("./file",0666);
int r_fd = open("file",O_RDONLY);
char buf[1024];
while(true)
{
int n = read(r_fd,buf,sizeof(buf)-1);
if(n > 0)
{
buf[n]='\0';
printf("Client say# %s\n",buf);
}
else if(n == 0) break;
else return 1;
}
close(r_fd);
unlink("file");
return 0;
}注:对于管道的创建与销毁在其中一端进行就行。
假设把文件client.cc生成的程序作为写端
#include<iostream>
#include<sys/types.h>
#include<sys/stat.h>
#include<cstdio>
#include<fcntl.h>
#include<unistd.h>
using namespace std;
int main()
{
int w_fd = open("file",O_WRONLY);
while(true)
{
string message;
cout<<"Please enter: ";
getline(cin,message);
write(w_fd,message.c_str(),message.size());
}
close(w_fd);
return 0;
}注意:该文侧重点在于讲解对命名管道的使用,所以以上代码中省略了对调用函数成功与否的判断,在实际开发中需要加以判断。
效果如下:

注1:管道的四种特性和四种通信情况,对于匿名管道和命名管道都是一样的。
注2:管道的生命周期随进程,本质是内核中的缓冲区,命名管道文件只是标识,用于让多个进程找到同一块缓冲区,删除后,之前已经打开管道的进程依然可以通信
非常感谢您能耐心读完这篇文章。倘若您从中有所收获,还望多多支持呀!