Linux 内核 (十二)进程间通讯 之 消息队列

前言

这个系列的上一篇介绍了进程间通讯关于管道相关的内容及代码实例,本章要介绍关于消息队列相关的内容.

消息队列交互图示

函数原型

cpp 复制代码
#include <sys/msg.h>
#include <sys/ipc.h>
//创建 or 打开队列 成功返回队列ID,失败返回-1
int msgget(key_t key,int flag);
//创建新队列的条件:没有与键值key相对应的消息队列,且flag中含有IPC_CREAT的标志位
//or key参数为IPC_PRIVATE

//添加消息:成功返回 0,失败返回-1
int msgsnd (int msqid,const void *ptr,size_t size,int flag);

//读取消息:成功返回 消息数据的长度,失败返回-1
int msgrcv(int msqid,void *ptr,size_t size,long type,int flag);

//控制消息队列:成功返回 0,失败返回-1
int msgctl(int msqid,int cmd,struct msqid_ds *buf);

消息队列api函数应用

msgGet.c

cpp 复制代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

struct msgBuf
{
    long mtype;
    char mtext[128];
};

int main(){
    struct msgBuf sendBuf = {888,"msg from que pjy "};
    int msgID = msgget(0x1234,IPC_CREAT|0777);
    if(msgID == -1){
        printf("get que failure\n");

    }
    msgsnd(msgID,&sendBuf,strlen(sendBuf.mtext),0);
    return 0;

}

msgSend.c

cpp 复制代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct msgBuf
{
    long mtype;
    char mtext[128];
};

int main(){
    struct msgBuf readBuf;
    //获取队列
    int msgID = msgget(0x1234,IPC_CREAT|0777);
    if(msgID == -1)
    {
        printf("get que failure !\n");

    }
    msgrcv(msgID,&readBuf,sizeof(readBuf.mtext),888,0);
    printf("read from que: %s \n",readBuf.mtext);
    return 0;

}

运行结果展示

相关推荐
聽雨23711 分钟前
02每日简报20250704
linux·科技·金融·生活·社交电子·娱乐·媒体
Maki Winster1 小时前
Peek-Ubuntu上Gif录制工具-24.04LTS可装
linux·ubuntu·peek
Maki Winster2 小时前
在 Ubuntu 下配置 oh-my-posh —— 普通用户 + root 各自使用独立主题(共享可执行)
linux·运维·ubuntu
守望时空332 小时前
Linux下KDE桌面创建自定义右键菜单
linux
l0sgAi2 小时前
vLLM在RTX50系显卡上部署大模型-使用wsl2
linux·人工智能
麟城Lincoln3 小时前
【RHCSA-Linux考试题目笔记(自用)】servera的题目
linux·笔记·考试·rhcsa
寻月隐君4 小时前
保姆级教程:Zsh + Oh My Zsh 终极配置,让你的 Ubuntu 终端效率倍增
linux·后端·命令行
XM-54584 小时前
2025微信小程序wxapkg解包全攻略
linux·运维·小程序
朗晴4 小时前
文本编辑器VIM的使用方法!
linux·运维·服务器
2401_8260976212 小时前
JavaEE-Linux环境部署
java·linux·java-ee