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;

}

运行结果展示

相关推荐
Yogurt_cry4 小时前
[树莓派4B] 闲置近10年的爱普生 L310 打印机爆改无线打印机
linux·物联网·树莓派
Johny_Zhao1 天前
OpenClaw中级到高级教程
linux·人工智能·信息安全·kubernetes·云计算·yum源·系统运维·openclaw
Sheffield2 天前
Docker的跨主机服务与其对应的优缺点
linux·网络协议·docker
Sheffield2 天前
Alpine是什么,为什么是Docker首选?
linux·docker·容器
Johny_Zhao3 天前
centos7安装部署openclaw
linux·人工智能·信息安全·云计算·yum源·系统运维·openclaw
haibindev3 天前
在 Windows+WSL2 上部署 OpenClaw AI员工的实践与踩坑
linux·wsl2·openclaw
0xDevNull4 天前
Linux切换JDK版本详细教程
linux
进击的丸子4 天前
虹软人脸服务器版SDK(Linux/ARM Pro)多线程调用及性能优化
linux·数据库·后端
Johny_Zhao6 天前
OpenClaw安装部署教程
linux·人工智能·ai·云计算·系统运维·openclaw