自己如何实现消息队列

 时间:2026-02-14 17:50:35

1、使用步骤:

 1)创建:key_t key=ftok(PATH,proj); int msgid=msgget(key,IPC_CREAT | 0600)

  2)发送:msgsnd(msgid,&msg,strlen(msg.mtext),0)

  3)接收:msgrcv(msgid,&msg,strlen(msg.mtext),msg.mtype,0)

  4)回收:msgctl(msgid,IPC_RMID,NULL)

自己如何实现消息队列

2、实现读消息的代码:

#include <stdio.h>

#include <unistd.h>

#include <string.h>

#include <stdlib.h>

#include <fcntl.h>

#include <sys/ipc.h>

#include <sys/msg.h>

#define TXT_SIZE 100

    

struct msgbuf

{

long type;

char txt[TXT_SIZE];

};

int main()

{

key_t key; //生成KEY

key=ftok("/home/lbh",10);

int msgid;

if(-1 == (msgid=msgget(key,IPC_CREAT | 0660)))//创建消息队列

{

perror("msgget");

exit(-1);

}

struct msgbuf msg;

bzero(&msg,sizeof(msg));

msgrcv(msgid,&msg,sizeof(msg.txt),1,0);//接收消息

printf("I get msg:%s\n",msg.txt);

    return 0;

}

自己如何实现消息队列

3、实现写消息的代码:

#include <stdio.h>

#include <unistd.h>

#include <string.h>

#include <stdlib.h>

#include <fcntl.h>

#include <sys/ipc.h>

#include <sys/msg.h>

#define TXT_SIZE 100

    

struct msgbuf

{

long type;

char txt[TXT_SIZE];

};

int main()

{

key_t key; //生成KEY

key=ftok("/home/lbh",10);

int msgid;

if(-1 == (msgid=msgget(key,IPC_CREAT | 0660)))//创建

{

perror("msgget");

exit(-1);

}

struct msgbuf msg;

bzero(&msg,sizeof(msg));

msg.type=1;

strcpy(msg.txt,"hello");

msgsnd(msgid,&msg,strlen(msg.txt),0);//发送消息

    return 0;

}

自己如何实现消息队列

4、在终端窗口中使用命令“gcc msgq_read.c -o read”和 “gcc msgq_write.c -o write”编译,使用命令“./read”和“./write”执行,效果如下:

自己如何实现消息队列

  • i386和X86的各是什么,有什么区别?
  • 怎么设置不允许远程连接到此计算机?
  • Win7文件夹下如何显示属性状态栏
  • B-LINK 随身wifi安装设置指南教程图解
  • Windows Server 2008 R2 搭建网站详细教程
  • 热门搜索
    微信接龙怎么往下接 怎么练胸肌 bootmgr is missing怎么解决 点怎么打 血小板低怎么治疗 胸太大怎么办 我的世界tnt怎么做 qq号忘记了怎么找回 雪蛤怎么吃 中南大学怎么样