Linux进程间通信(四).命名管道

发布时间:2026/9/25 19:21:59
Linux进程间通信(四).命名管道 一.何谓命名管道二.如何创建命名管道文件1.命名管道可以从命令⾏上创建命令⾏⽅法是使⽤下⾯这个命令$ mkfifo filename2.命名管道也可以从程序⾥创建相关函数有int mkfifo(const char *filename,mode_t mode);mode 指定FIFO文件的初始权限八进制数字和 open 、 chmod 权限格式一样。1. 0666 最常用-rw‑rw‑rw‑所有者、组、其他用户都可读可写。2. 0600-rw-------只有创建者本人能读写其他人完全不能访问。3. 0664-rw‑rw‑r--用户、组读写其他只可读。创建成功返回0失败-1。3.用unlink 文件名可以删除管道。(既可以作为指令也可以作为接口)删除成功返回0失败-1。三.实现进程间通信//client.cc #includeiostream #includestring #includesys/types.h #includesys/stat.h #includefcntl.h #includecomm.hpp #includeunistd.h int main() { int fd open(FIFO_FILE,O_WRONLY); if(fd 0) { std::cerr 打开失败 std::endl; return 2; } while(true) { std::cout Please enter# ; std::string message; std::cin message; int n write(fd,message.c_str(),message.size()); if(n 0) { } } close(fd); return 0; }//server.cc #includeiostream #includestring #includesys/types.h #includesys/stat.h #includefcntl.h #includecomm.hpp #includeunistd.h int main() { umask(0); int n mkfifo(FIFO_FILE,0666); if(n ! 0) { std::cerr 打开失败 std::endl; return 1; } int fd open(FIFO_FILE,O_RDONLY); if(fd 0) { std::cerr 创建失败 std::endl; return 2; } char buffer[1024]; while(true) { int n read(fd,buffer,sizeof(buffer) - 1); if(n 0) {//读取成功 buffer[n] 0;//把\0添加回来。 std::cout Client say# buffer std::endl; } } close(fd); return 0; }