linux系统编程:进程间通信-fifo

来源:互联网 发布:红警网络进不去 编辑:程序博客网 时间:2024/03/29 13:30

                          进程间通信-fifo

进程间通信的另一种方式是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 myfifoid=1,name=zhangxiangid=2,name=zhangxiangid=3,name=zhangxiangid=4,name=zhangxiangid=5,name=zhangxiangid=6,name=zhangxiangid=7,name=zhangxiangid=8,name=zhangxiang^c 



以上示例中,一个进程不断地向fifo中写入结构体类型的数据,另一个进程不断地从fifo中读出数据,从而达到进程间的通信。



CCPP Blog 目录


1 0
原创粉丝点击