歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux消息隊列

Linux消息隊列

日期:2017/2/28 16:10:00   编辑:Linux教程

所謂消息隊列就是指一個消息鏈表。

int msgget(key_t, int flag):創建和打開隊列

int msgsnd(int msqid, struct msgbuf *msgp, size_t msgsz, int flag):發送消息,msgid是消息隊列的id,msgp是消息內容所在的緩沖區,msgsz是消息的大小,msgflg是標志。

int msgrcv(int msqid, struct msgbuf *msgp, size_t msgsz, long msgtyp, int flag):接受消息,msgtyp是期望接收的消息類型。

int msgctl(int msqid, int cmd, struct msqid_ds *buf):控制

  1. #include <sys/types.h>
  2. #include <sys/ipc.h>
  3. #include <sys/msg.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include <string.h>
  8. #define BUFSZ 512
  9. struct message{ //消息結構體
  10. long msg_type;
  11. char msg_text[BUFSZ];
  12. };
  13. int main()
  14. {
  15. int qid;
  16. key_t key;
  17. int len;
  18. struct message msg;
  19. if((key=ftok(".",'a'))==-1) //ftok獲得一個key
  20. {
  21. perror("ftok");
  22. exit(1);
  23. }
  24. if((qid=msgget(key,IPC_CREAT|0666))==-1){ //創建一個消息隊列
  25. perror("msgget");
  26. exit(1);
  27. }
  28. printf("opened queue %d\n",qid);
  29. puts("Please enter the message to queue:");
  30. if((fgets(msg.msg_text,BUFSZ,stdin))==NULL) // 從標准輸入獲取輸入
  31. {
  32. puts("no message");
  33. exit(1);
  34. }
  35. msg.msg_type = getpid();
  36. len = strlen(msg.msg_text);
  37. if((msgsnd(qid,&msg,len,0))<0){ //發送消息
  38. perror("message posted");
  39. exit(1);
  40. }
  41. if(msgrcv(qid,&msg,BUFSZ,0,0)<0){ //接收消息
  42. perror("msgrcv");
  43. exit(1);
  44. }
  45. printf("message is:%s\n",(&msg)->msg_text);
  46. if((msgctl(qid,IPC_RMID,NULL))<0){ //刪除消息
  47. perror("msgctl");
  48. exit(1);
  49. }
  50. exit(0);
  51. }
Copyright © Linux教程網 All Rights Reserved