Linux基础编程 消息队列 msgsnd
Linux基础编程 消息队列 msgsnd
实际上,消息队列常常保存在链表结构中。拥有权限的进程可以向消息队列中写入或读取消息。
消息队列本身是异步的,它允许接收者在消息发送很长时间后再取回消息,这和大多数通信协议是不同的。例如WWW中使用的HTTP协议是同步的,因为客户端在发出请求后必须等待服务器回应。然而,很多情况下我们需要异步的通信协议。比如,一个进程通知另一个进程发生了一个事件,但不需要等待回应。但消息队列的异步特点,也造成了一个缺点,就是接收者必须轮询消息队列,才能收到最近的消息。
和信号相比,消息队列能够传递更多的信息。与管道相比,消息队列提供了有格式的数据,这可以减少开发人员的工作量。但消息队列仍然有大小限制。
包含文件
1、msg.c
2、msg.h
3、thread.c
源文件1 msg.c
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/msg.h>
- #define __DEBUG
- #ifdef __DEBUG
- #define DBG(fmt,args...) fprintf(stdout, fmt, ##args)
- #else
- #define DBG(fmt,args...)
- #endif
- #define ERR(fmt,args...) fprintf(stderr, fmt, ##args)
- /*
- 消息队列初始化
- msgKey:消息队列键值
- qid:返回值,消息队列id
- */
- int Msg_Init( int msgKey )
- {
- int qid;
- key_t key = msgKey;
- /*
- 消息队列并非私有,因此此键值的消息队列很可能在其他进程已经被创建
- 所以这里尝试打开已经被创建的消息队列
- */
- qid = msgget(key,0);
- if(qid < 0){
- /*
- 打开不成功,表明未被创建
- 现在可以按照标准方式创建消息队列
- */
- qid = msgget(key,IPC_CREAT|0666);
- DBG("Create msg queue id:%d\n",qid);
- }
- DBG("msg queue id:%d\n",qid);
- return qid;
- }
- /*
- 杀死消息队列
- qid:消息队列id
- */
- int Msg_Kill(int qid)
- {
- msgctl(qid, IPC_RMID, NULL);
- DBG("Kill queue id:%d\n",qid);
- return 0;
- }
|
评论暂时关闭