电子说
在两个终端里用 gcc 分别编译运行上面两个文件,可以看到输出结果如下:
[$ ./write_fifo ]
I am 7872 process
Send message: Process 7872's time is Mon Jan 16 18:00:23 2023
Send message: Process 7872's time is Mon Jan 16 18:00:24 2023
Send message: Process 7872's time is Mon Jan 16 18:00:25 2023
Send message: Process 7872's time is Mon Jan 16 18:00:26 2023
Send message: Process 7872's time is Mon Jan 16 18:00:27 2023
Send message: Process 7872's time is Mon Jan 16 18:00:28 2023
Send message: Process 7872's time is Mon Jan 16 18:00:29 2023
Send message: Process 7872's time is Mon Jan 16 18:00:30 2023
Send message: Process 7872's time is Mon Jan 16 18:00:31 2023
Send message: Process 7872's time is Mon Jan 16 18:00:32 2023
[$ ./write_fifo ]
I am 7872 process
Send message: Process 7872's time is Mon Jan 16 18:00:23 2023
Send message: Process 7872's time is Mon Jan 16 18:00:24 2023
Send message: Process 7872's time is Mon Jan 16 18:00:25 2023
Send message: Process 7872's time is Mon Jan 16 18:00:26 2023
Send message: Process 7872's time is Mon Jan 16 18:00:27 2023
Send message: Process 7872's time is Mon Jan 16 18:00:28 2023
Send message: Process 7872's time is Mon Jan 16 18:00:29 2023
Send message: Process 7872's time is Mon Jan 16 18:00:30 2023
Send message: Process 7872's time is Mon Jan 16 18:00:31 2023
Send message: Process 7872's time is Mon Jan 16 18:00:32 2023
上面的例子可以扩展成 客户端进程—服务端进程通信的实例,write_fifo的作用类似于客户端,可以打开多个客户端向一个服务器发送请求信息,read_fifo类似于服务器,它适时监控着FIFO的读端,当有数据时,读出并进行处理,但是有一个关键的问题是,每一个客户端必须预先知道服务器提供的FIFO接口,下图显示了这样的操作:
消息队列,是消息的链接表,存放在内核中。一个消息队列由一个标识符(即队列ID)来标识。
// 创建或打开消息队列:成功返回队列ID,失败返回-1
intmsgget(key_t key, int flag);
// 添加消息:成功返回0,失败返回-1
intmsgsnd(int msqid, constvoid ptr, size_t size, int flag);
// 读取消息:成功返回消息数据的长度,失败返回-1
intmsgrcv(int msqid, void* ptr, size_t size, long type, int flag);
// 控制消息队列:成功返回0, 失败返回-1
intmsgctl(int msqid, int cmd, struct msqid_ds * buf);
在以下两种情况下,msgget将创建一个新的消息队列:
IPC_CREAT
标志位。函数msgrcv在读取消息队列时,type参数有下面几种情况:
可以看出,type值非 0 时用于以非先进先出次序读消息。也可以把 type 看做优先级的权值。(其他的参数解释,请自行Google之)
全部0条评论
快来发表一下你的评论吧 !