【C++ 消息队列】

发布时间:2024年01月21日

创建

#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>

int main(){
  int msgid;

  msgid = msgget(IPC_PRIVATE, 0600);
  if(msgid < 0){
    perror("msgget");
    return 1;
  }

  printf("%d\n", msgid);
  return 0;
}

king@ubuntu:~/share/ms_examples$ ./cmessageque 
1
king@ubuntu:~/share/ms_examples$ ipcs -q

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages    
0x00000000 1          king       600 

写入msg queue

#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>

#define MTEXTSIZE 10

int main(int argc, char* argv[]){
  int msgid;
  struct msgbuf{
    long mtype;
    char mtext[MTEXTSIZE];
  }mbuf;

  if(argc != 2){
    printf("wrong argc");
    return 1;
  }

  msgid = atoi(argv[1]);

  mbuf.mtype = 777;
  memset(mbuf.mtext, 0, sizeof(mbuf.mtext));
  mbuf.mtext[0] = 'A';

  if(msgsnd(msgid, &mbuf, MTEXTSIZE, 0) != 0){
    perror("msgsnd");
    return 1;
  }

  return 0;
}


king@ubuntu:~/share/ms_examples$ ./imessageque 1
king@ubuntu:~/share/ms_examples$ ipcs -q

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages    
0x00000000 1          king       600        10           1    

读取

#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>

#define MTEXTSIZE 10

int main(int argc, char* argv[]){
  int msgid, msgtype;
  
  struct msgbuf{
    long mtype;
    char mtext[MTEXTSIZE];
  }mbuf;

  if(argc != 3){
    printf("wrong argc");
    return 1;
  }

  msgid = atoi(argv[1]);
  msgtype = atoi(argv[2]);

  if(msgrcv(msgid, &mbuf, MTEXTSIZE, msgtype, 0) <= 0){
    perror("msgrcv");
    return 1;
  }

  printf("%c\n", mbuf.mtext[0]);
  return 0;
}

king@ubuntu:~/share/ms_examples$ ./omessageque 1 777
A
king@ubuntu:~/share/ms_examples$ ipcs -q

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages    
0x00000000 1          king       600        0            0     

删除 msg queue

#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>

int main(int argc, char* argv[]){
  int msgid;
  msqid_ds mds;

  if(argc != 2){
    printf("wrong argv\n");
    return 1;
  }

  msgid = atoi(argv[1]);

  if(msgctl(msgid, IPC_RMID, &mds) != 0){
    perror("msgctl");
    return 1;
  }

  return 0;
}






king@ubuntu:~/share/ms_examples$ ./rmessageque 1
king@ubuntu:~/share/ms_examples$ ipcs -q

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages 

或者 ipcrm -q id 删除

文章来源:https://blog.csdn.net/weixin_45397344/article/details/135733805
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。