linux系统编程:进程间通信-fifo
2015-07-15 18:23
429 查看
进程间通信-fifo
进程间通信的另一种方式是fifo。fifo是另一种管道:有名管道。从名字可以看出,它也是队列。
使用fifo通信前,得先创建fifo
随后只需对myfifo像文件一样使用就行。fifo_w.c
fifo_r.c
测试
以上示例中,一个进程不断地向fifo中写入结构体类型的数据,另一个进程不断地从fifo中读出数据,从而达到进程间的通信。
CCPP Blog 目录
进程间通信的另一种方式是fifo。fifo是另一种管道:有名管道。从名字可以看出,它也是队列。
使用fifo通信前,得先创建fifo
$ mkfifo myfifo
随后只需对myfifo像文件一样使用就行。fifo_w.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/fcntl.h> struct stu { int id; char name[20]; }; int main(int argc, char **argv) { if(argc != 2) { fprintf(stderr, "usage:./app fifo\n"); exit(1); } int fd; if((fd = open(argv[1], O_WRONLY)) < 0) { fprintf(stderr, "open:can not open file:%s\n", argv[1]); exit(1); } struct stu zx = {0, "zhangxiang"}; int id = 0; while(1) { id++; zx.id = id; write(fd, &zx, sizeof(zx)); sleep(1); } close(fd); return 0; }
fifo_r.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/fcntl.h> struct stu { int id; char name[20]; }; int main(int argc, char **argv) { if(argc != 2) { fprintf(stderr, "usage:./app fifo"); exit(1); } int fd; if((fd = open(argv[1], O_RDONLY)) < 0) { fprintf(stderr, "open:can not open file:%s", argv[1]); exit(1); } struct stu zx; while(1) { read(fd, &zx, sizeof(zx)); printf("id=%d,name=%s\n", zx.id, zx.name); sleep(1); } close(fd); return 0; }
测试
$ gcc fifo_w.c -o fifo_w $ gcc fifo_r.c -o fifo_r $ fifo_w myfifo //另开一终端 $ fifo_r myfifo id=1,name=zhangxiang id=2,name=zhangxiang id=3,name=zhangxiang id=4,name=zhangxiang id=5,name=zhangxiang id=6,name=zhangxiang id=7,name=zhangxiang id=8,name=zhangxiang ^c
以上示例中,一个进程不断地向fifo中写入结构体类型的数据,另一个进程不断地从fifo中读出数据,从而达到进程间的通信。
CCPP Blog 目录
相关文章推荐
- Linux-阿
- linux上安装subversion
- Linux——常用命令详解
- Linux——常用命令详解
- linux内存屏障浅析
- centos 下yum lock的解决办法
- 嵌入式linux之按键驱动程序
- Linux ls命令参数详解 <转>
- Linux 服务器安全技巧
- linux中时间设置date、hwclock、clock
- centos中mysql远程连接失败解决方案
- Linux下的passwd和shadow文件
- Linux 服务器安全技巧
- 查看linux发行版本
- Linux TOP命令各参数详解
- 每天进步一点点——linux——awk
- 【Linux系统】嵌入式系统中文环境设置
- Linux内核中双向链表的经典实现
- CentOS yum 命令出现 [Errno 14] curl#6 - "Couldn't resolve host ..." 的解决方法
- open()函数 linux中open函数使用