Linux学习笔记-消息队列的打开、创建、控制

140 篇文章 11 订阅

目录

 

 

打开或创建消息队列

消息队列的控制

发送消息

举个栗子


 

打开或创建消息队列

#include <sys/msg.h>
int msgget(key_t key, int flag);

//返回:成功返回内核中消息队列的标识ID,出错返回-1

参数:

key:用户指定的消息队列的键值;

flag:IPC_CREAT、IPC_EXCL等权限组合;

 

若创建消息队列,key可指定键值,也可将之设置为IPC_PRIVATE。若打开进行查询,则key不能为0必须是一个非零的值否则是查询不到的。

 

消息队列的控制

#include <sys/msg.h>
int msgctl(int msgid, int cmd, struct msqid_ds *buf);
//返回:成功返回0,出错返回-1

参数:

msgid:消息队列ID;

buf:消息队列属性指针;

cmd:

     1.IPC_STAT:获取消息的属性,取出队列msqid_ds结构,并将其存放到uf指向的结构体中;

     2. IPC_SET:设置属性;

     3. IPC_RMID:删除队列。

 

发送消息

#include <sys/msg.h>
int msgsnd(int msgqid, const void *ptr, size_t nbytes, int flag);
//返回值:成功0,出错-1


ptr:

struct mymsg{

    long mytype;        //消息类型
    char mtext[512];    //发送的数据
};

在Linux中,消息的最大长度是4056字节,其中mytype是4字节;

flag:0为阻塞,IPC_NOWAIT为非阻塞;

 

举个栗子

源码如下:

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

typedef struct{
        long type; //消息类型
        int start; //消息数据本身 包括 start 和 end
        int end;
}MSG;

int main(int argc, char *argv[]){

        if(argc < 2){

                printf("usage: %s key\n", argv[0]);
                exit(1);
        }

        key_t key = atoi(argv[1]);
        printf("key: %d\n", key);

        //创建消息队列
        int msq_id;
        if((msq_id = msgget(key, IPC_CREAT | IPC_EXCL | 0777)) < 0){

                perror("msgget error");
        }
        printf("msq id: %d\n", msq_id);

        //定义要发送的消息
        MSG m1 = {4, 4, 400};
        MSG m2 = {2, 2, 200};
        MSG m3 = {1, 1, 100};

        //发送消息到消息队列
        if(msgsnd(msq_id, &m1, sizeof(MSG) - sizeof(long), IPC_NOWAIT) < 0){

                perror("msgsnd error");
        }
        if(msgsnd(msq_id, &m2, sizeof(MSG) - sizeof(long), IPC_NOWAIT) < 0){

                perror("msgsnd error");
        }
        if(msgsnd(msq_id, &m3, sizeof(MSG) - sizeof(long), IPC_NOWAIT) < 0){

                perror("msgsnd error");
        }

        //发送消息后获取消息队列中的消息总数
        struct msqid_ds ds;
        if(msgctl(msq_id, IPC_STAT, &ds) < 0){

                perror("msgctl error");
        }
        printf("msg total: %ld\n", ds.msg_qnum);

        exit(0);
}

运行截图如下:

查看ipc

删除他!

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值