Linux基础编程 消息队列 msgsnd


实际上,消息队列常常保存在链表结构中。拥有权限的进程可以向消息队列中写入或读取消息。

消息队列本身是异步的,它允许接收者在消息发送很长时间后再取回消息,这和大多数通信协议是不同的。例如WWW中使用的HTTP协议是同步的,因为客户端在发出请求后必须等待服务器回应。然而,很多情况下我们需要异步的通信协议。比如,一个进程通知另一个进程发生了一个事件,但不需要等待回应。但消息队列的异步特点,也造成了一个缺点,就是接收者必须轮询消息队列,才能收到最近的消息。

和信号相比,消息队列能够传递更多的信息。与管道相比,消息队列提供了有格式的数据,这可以减少开发人员的工作量。但消息队列仍然有大小限制。

包含文件
1、msg.c
2、msg.h
3、thread.c

源文件1 msg.c

  1. #include <stdio.h>   
  2. #include <stdlib.h>   
  3. #include <unistd.h>   
  4. #include <sys/msg.h>   
  5.   
  6. #define __DEBUG   
  7. #ifdef __DEBUG   
  8. #define DBG(fmt,args...) fprintf(stdout,  fmt,  ##args)   
  9. #else   
  10. #define DBG(fmt,args...)   
  11. #endif   
  12. #define ERR(fmt,args...) fprintf(stderr,  fmt,  ##args)   
  13.   
  14. /* 
  15. 消息队列初始化 
  16. msgKey:消息队列键值 
  17. qid:返回值,消息队列id 
  18. */  
  19. int Msg_Init( int msgKey )  
  20. {  
  21.     int qid;  
  22.     key_t key = msgKey;  
  23.     /* 
  24.     消息队列并非私有,因此此键值的消息队列很可能在其他进程已经被创建 
  25.     所以这里尝试打开已经被创建的消息队列 
  26.     */  
  27.     qid = msgget(key,0);  
  28.     if(qid < 0){  
  29.         /* 
  30.         打开不成功,表明未被创建 
  31.         现在可以按照标准方式创建消息队列 
  32.         */  
  33.         qid = msgget(key,IPC_CREAT|0666);  
  34.         DBG("Create msg queue id:%d\n",qid);  
  35.     }  
  36.     DBG("msg queue id:%d\n",qid);  
  37.     return qid;  
  38. }  
  39. /* 
  40. 杀死消息队列 
  41. qid:消息队列id 
  42. */  
  43. int Msg_Kill(int qid)  
  44. {  
  45.     msgctl(qid, IPC_RMID, NULL);  
  46.     DBG("Kill queue id:%d\n",qid);  
  47.     return 0;  
  48. }  
  • 1
  • 2
  • 3
  • 4
  • 下一页

相关内容