Linux网络编程, 使用消息队列的demo (msgget, msgsnd, msgrcv)

一个使用消息队列的demo

代码描述

  • demo任务: 父进程fork得到子进程, 子进程往消息队列发送消息, 父进程从消息队列取消息
  • 环境: ubuntu20.04, C++14
#include <sys/socket.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/msg.h>
#include <string.h>
#define BUFFER_SIZE 256

/**
 * @brief  自定义的消息队列的消息结构,
 * @note    这个结构必须先是long再是char[]
 * * (https://man7.org/linux/man-pages/man3/msgrcv.3p.html)
 * @retval None
 */
struct mymsg
{
    long mtype; /* Message type. */
    char mtext[BUFFER_SIZE];
};

int main(int argc, char const *argv[])
{
    int queid = msgget(IPC_PRIVATE, IPC_CREAT | IPC_EXCL);
    pid_t pid = fork();
    if (pid == 0) // 子进程发消息到消息队列
    {
        // 定义用于发送的消息结构体
        mymsg child_buf;
        child_buf.mtype = 1;
        strcpy(child_buf.mtext, "hello world");
        printf("child sent msg: %s\n", child_buf.mtext);
        int ret = msgsnd(queid, &child_buf, strlen(child_buf.mtext), IPC_NOWAIT);
        assert(ret != -1);
    }
    else
    {
        // 父进程不断问询消息队列, 获取消息
        while (1)
        {
            mymsg msg_rcv; // 用于接收的消息结构体
            int ret = msgrcv(queid, &msg_rcv, BUFFER_SIZE, 0, IPC_NOWAIT);
            if (ret != -1)
            {
                printf("parent received msg: %s\n", msg_rcv.mtext);
                break;
            }
        }
    }
    return 0;
}

运行结果

child sent msg: hello world
parent received msg: hello world
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值