消息队列的接受发送方式

1、int msgget(key_t key, int flg);

创建队列

key为消息队列的键值,为了找到相应的队列,flg为消息队列的打开方式

返回值:成功返回0,失败返回-1

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

发送队列

msqid为队列的ID号,*msgp为消息,msgsz为消息的字节大小,msgflg为标志位(口令)

返回值:成功返回0,失败返回-1

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

接收队列

msqid为队列的ID号,*msgp为消息,msgsz为消息的字节大小,msgflg为标志位(口令)

返回值:成功返回消息数据的长度,失败返回-1

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

控制队列

返回值:成功返回0,失败返回-1

发送消息队列

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
struct msgbuf{

        long mtype;
        char mtext[128];
};

int main() 
{
        //get 
        struct msgbuf sendbuf = {888,"this is message from que"};
        struct msgbuf readbuf;

        int msgId = msgget(0x1234,IPC_CREAT|0777);        //创建一个队列
        if(msgId == -1){
                printf("get que failer\n");        //判断返回值
        }
        msgsnd(msgId,&sendbuf,strlen(sendbuf.mtext),0);        //发送队列的数据(sendbuf)
        printf("send over\n");

        msgrcv(msgId,&readbuf,sizeof(readbuf.mtext),988,0);        //接收队列的数据(readbuf)
        printf("return from read:%s\n",readbuf.mtext);


        return 0;
}

接受消息队列

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
struct msgbuf{

        long mtype;
        char mtext[128];
};

int main()
{
        //get 
        struct msgbuf sendbuf = {988,"thank you for your reach"};
        struct msgbuf readbuf;

        int msgId = msgget(0x1234,IPC_CREAT|0777);       //创建一个队列
        if(msgId == -1){
                printf("get que failer\n");
        }                //判断消息队列的返回值
        msgrcv(msgId,&readbuf,sizeof(readbuf.mtext),888,0);        //接收队列的数据(readbuf)
//      msgsnd(msgId,&sendbuf,strlen(sendbuf.mtext),0);
        printf("read from que:%s\n",readbuf.mtext);

        msgsnd(msgId,&sendbuf,strlen(sendbuf.mtext),0);        //发送队列的数据(sendbuf)

        return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值