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 文件夹


  • 相关阅读:
    wp8 入门到精通
    C# 从入门到精通
    wp8 json2csharp
    wp8 安装.Net3.5
    delphi资源文件制作及使用详解
    delphi弹出选择对话框选择目录SelectDirectory 函数
    delphi 判断WIN8 , WIN8.1 , WIN10 系统版本
    外壳扩展创建快捷方式和获取快捷方式的目标对象
    文本究竟是使用哪种字
    用Delphi创建服务程序
  • 原文地址:https://www.cnblogs.com/zsychanpin/p/6748143.html
Copyright © 2011-2022 走看看