Skip to content

消息队列 #44

@Zhonghe-zhao

Description

@Zhonghe-zhao

在linux查询指令

linux手册:

man msgget 关于消息对立中 msgget的系统调用文档!
man msgsnd 关于消息对立中 msgsnd的系统调用文档!
里面包含

int msgget(key_t key, int msgflg);

int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);

ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);

int msgctl(int msqid, int cmd, struct msqid_ds *buf);

消息队列的创建 于 发送

#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <fcntl.h>
#include "mymsg.h"
/*

*/

int main()
{
    key_t key;
    int msgid;
    int fd;

    fd = open(MSG_PATH, O_CREAT | O_RDONLY, 0644);
    if (fd < 0)
    {
        ERR_EXIT("open");
    }
    close(fd);
    key = ftok(MSG_PATH, 0);
    if (key < 0)
    {
        ERR_EXIT("ftok");
    }
    printf("Generated IPC key: 0x%x\n", key);
    msgid = msgget(key, 0644 | IPC_CREAT);
    if (msgid < 0)
    {
        ERR_EXIT("msgget");
    }
    printf("msgid:%d\n",msgid);
        exit(EXIT_SUCCESS);



struct msgbuf buf;
buf.mtype = MTYPE;
buf.mdata.idno = rand()%1000;
buf.mdata.grander = (rand()%2) ? 'MAN' : 'WOMEN';
snprinft(buf.mdata.pname, 64, "Name-%03%d", rand()%1000);

msgsnd(msgid, &buf, sizeof(buf.mdata), 0);
}

ipcs -q

是 Linux/Unix 系统中的一个命令,用于 查看当前系统中所有的 System V 消息队列(Message Queues)信息。它是进程间通信(IPC)管理的重要工具之一。

从消息队列中获取消息

#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <fcntl.h>
#include "mymsg.h"
/*

*/

int main()
{
    key_t key;
    int msgid;
    int fd;

    fd = open(MSG_PATH, O_CREAT | O_RDONLY, 0644);
    if (fd < 0)
    {
        ERR_EXIT("open");
    }
    close(fd);
    key = ftok(MSG_PATH, 0);
    if (key < 0)
    {
        ERR_EXIT("ftok");
    }
    printf("Generated IPC key: 0x%x\n", key);
    msgid = msgget(key, 0644 | IPC_CREAT);
    if (msgid < 0)
    {
        ERR_EXIT("msgget");
    }
    printf("msgid:%d\n", msgid);

    struct msgbuf buf;
    msgrcv(msgid, &buf, sizeof(Data), MTYPE, 0);
    printf("%d\t%c\t%s\n",buf.mdata.idno, buf.mdata.grander, buf.mdata.pname);
    exit(EXIT_SUCCESS);
}

如果 队列中没有消息 还被一直读取将会阻塞!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions