【C++ 消息队列】

创建

#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 删除

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值