命名管道理解与简单C实现
来源:互联网 发布:统计师的python日记 编辑:程序博客网 时间:2024/06/08 19:51
命名管道主要解决进程间消息传递的问题。 虽然是以文件的形式, 但是实际上消息仍然是存储在内存中的, 这也是无论何时查看管道文件都是0kb的原因。
以下是两个实例fifo_write.c和fifo_read.c:
fifo_read.c:
#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <limits.h>#include <string.h>#include <unistd.h>#define MYFIFO "myfifo" /* 有名管道文件名*/#define MAX_BUFFER_SIZE PIPE_BUF/*常量PIPE_BUF 定义在于limits.h中*/char buff[MAX_BUFFER_SIZE];int fd;int nread;void f_read(){ fd = open(MYFIFO, O_RDONLY); memset(buff, 0, sizeof(buff)); nread = read(fd, buff, MAX_BUFFER_SIZE); printf("read:'%s' length:%d\n", buff, nread); close(fd);}int main(){ if (access(MYFIFO, F_OK) == -1){ if ((mkfifo(MYFIFO, 0666) < 0) && (errno != EEXIST)){ printf("Cannot create fifo file\n"); exit(1); } } while (1){ f_read(); } exit(0);}fifo_write.c:
#include<sys/types.h>#include<sys/stat.h>#include<errno.h>#include<fcntl.h>#include<stdio.h>#include<stdlib.h>#include<limits.h>#include<unistd.h>#include<string.h>#define MYFIFO "myfifo"#define MAX_BUFFER_SIZE PIPE_BUFint fd;char buff[MAX_BUFFER_SIZE];int nwrite;void f_write(){ fd = open(MYFIFO, O_WRONLY); write(fd, buff, MAX_BUFFER_SIZE); close(fd);}int main(int argc, char * argv[]){ if (access(MYFIFO, F_OK) == -1){ if ((mkfifo(MYFIFO, 0666) < 0) && (errno != EEXIST)){ printf("Cannot create fifo file\n"); exit(1); } } while(gets(buff)!=EOF){ f_write(); }exit(0);}Centos 7下编译:
gcc -o fifo_write fifo_write.c
gcc -o fifo_read fifo_read.c
运行程序:
在fifo_write下输出传输的文本, fifo_read下会读出对应的信息。
另外此种消息传递是阻塞式的, 先打开fifo_read或fifo_write都是一样的, 程序都会正常运行。
其它的相关管道的知识, 可以查阅相关的资料。 但是关于管道的使用, 容易出现问题, 项目中一旦出现阻塞不容易处理, 所以最终自己还是放弃了用管道来进行数据的传输。
阅读全文
0 0
- 命名管道理解与简单C实现
- linux c之命名管道简单使用
- 匿名管道 与 命名管道
- 匿名管道与命名管道
- 命名管道与Mailslot
- 信号与命名管道
- Linux下利用命名管道实现简单的聊天室
- Linux C命名管道实现进程间通信
- PHP服务器端通过命名管道与C/C++程序通信
- linux c 中简单的管道实现
- 命名管道的简单使用
- 命名管道的简单使用
- linux 简单的命名管道
- Linux----进程间通信-管道与两个命名管道实现进程双向通信
- 命名管道(代码实现)
- Unix管道与命名FIFO
- ASP.NET 管道事件与HttpModule, HttpHandler简单理解
- ASP.NET 管道事件与HttpModule, HttpHandler简单理解
- js -- 打开新窗口(window.open)、关闭窗口(window.close)
- mapred-site.xml参数配置详情
- JAVA 基础
- PYTHON 抓去京东,百度的数据
- java 获取代理的真实ip
- 命名管道理解与简单C实现
- mySQL存储千万条数据
- Java操作文件输出为字符串以及字符串输出为文件
- python短网址转换
- 玩转Android之数据库框架greenDAO3.0使用指南
- TCP协议详解
- android 一键锁屏
- [LeetCode] 206-Reverse Linked List
- linux命令的使用