进程间通信(IPC)2 ------ 有名管道
来源:互联网 发布:刀剑神域第二季 知乎 编辑:程序博客网 时间:2024/05/21 18:44
管道的一个不足之处是没有名字,因此只能在具有亲缘关系的进程之间通信。而“有名管道”与此不同,它提供了一个路径名与之关联,作为一个设备文件存在,即使无亲缘关系的进程之间,只要能访问该路径,也可以通过FIFO进行通信。FIFO总是按照先进先出的原则工作,第一个被写入的数据将首先从管道中读出。
函数原型:
#include <sys/types.h>#include <sys/stat.h>int mkfifo(const char *path,mode_t mode);
path为创建有名管道的路径名;mode为创建有名管道的模式,指明其存取权限。函数调用成功返回0,失败返回-1。
使用一个存在的有名管道之前,需要用open()将其打开。因为有名管道是一个存在于硬盘上的文件,而管道是存在于内存中的特殊文件。
以下程序演示有名管道在无亲缘关系的进程之间如何通信。
//procwriter.c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <fcntl.h>#include <sys/types.h>#include <sys/stat.h>#define FIFO_NAME"myfifo"#define BUF_SIZE1024int main(void){int fd;charbuf[BUF_SIZE] = "Hello procwrite, I come from process named procread!";umask(0);//指明创建一个有名管道且存取权限为0666,即创建者、与创建者同组的用户、其他用户对该有名管道的访问权限都是可读可写if (mkfifo (FIFO_NAME, S_IFIFO | 0666) == -1){perror ("mkfifo error!");exit (1);}if((fd = open (FIFO_NAME, O_WRONLY) ) == -1)/*以写方式打开FIFO*/{perror ("fopen error!");exit (1);}write (fd, buf, strlen(buf)+1); /*向FIFO写数据*/close (fd);exit (0);}
procreader.c
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/stat.h>#include <fcntl.h>#include <sys/types.h>#define FIFO_NAME "myfifo"#define BUF_SIZE 1024int main(void){ int fd; char buf[BUF_SIZE]; umask (0); fd = open(FIFO_NAME, O_RDONLY); read (fd, buf, BUF_SIZE); printf ("Read content: %s\n", buf); close (fd); exit (0);}
首先运行procwrite(运行后处于阻塞状态),打开另一个终端运行程序procread。结果如下:
阅读全文
0 0
- 进程间通信(IPC)2 ------ 有名管道
- 进程间通信IPC之--无名管道(pipe)和有名管道(fifo)
- APUE读书笔记---进程间通信(IPC)之管道和有名管道(FIFO)
- 进程间通信(二)有名管道
- 进程间通信(1)-有名管道
- 进程间通信-管道(有名管道和无名管道)
- 2、进程间通信-FIFO(有名管道)
- 进程间通信--有名管道
- 进程间通信-有名管道
- Linux--进程间通信(管道及有名管道FIFO)
- Linux--进程间通信(管道及有名管道FIFO)
- Linux--进程间通信(管道及有名管道FIFO)
- 进程间通信(无名管道,有名管道,共享内存)
- [IPC]通信有名管道FIFO
- 【IPC通信】有名管道FIFO
- IPC通信之有名管道
- 进程通信--有名管道
- Linux 进程间通讯(IPC)详细总结 2有名管道。
- angular 的 下拉加载
- SAP作业价格计算
- cscope file does not exist 错误解决办法
- Nepire的校OJ入门题解—17蓝桥选拔篇(三)
- SpringCloud网关Zuul
- 进程间通信(IPC)2 ------ 有名管道
- JAVA快速批量删除文件
- mac下载的文件后缀@问题:-rw-r--r--@
- rabbitmq lazy-queues测试
- python 浅copy和深deepcopy
- JAVA 枚举
- python在window上的环境搭建
- Unity3d游戏开发注意事项
- Day14