zoukankan      html  css  js  c++  java
  • linux系统编程:进程间通信-fifo

                              进程间通信-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
    ");
    		exit(1);
    	}
    	int fd;
    	if((fd = open(argv[1], O_WRONLY)) < 0)
    	{
    		fprintf(stderr, "open:can not open file:%s
    ", 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
    ", 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 文件夹


  • 相关阅读:
    href 和src 的区别
    一道返回不重复数组的测试题
    使用Node.js+Socket.IO搭建WebSocket实时应用
    WebSocket 是什么原理?为什么可以实现持久连接?
    图片异步加载
    30分钟新手git教程
    通过ajax异步调用返回值
    [JS] 让人犯晕的JavaScript变量赋值
    javaScript字符串操作
    (String),toString(),String.valueOf()
  • 原文地址:https://www.cnblogs.com/zsychanpin/p/6748143.html
Copyright © 2011-2022 走看看