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;

}

运行结果展示

相关推荐
東雪蓮☆2 分钟前
使用Shell脚本实现Linux系统资源监控邮件告警
linux·运维·服务器
EleganceJiaBao16 分钟前
【Neovim】Vi、Vim、Neovim 与 LazyVim:发展史
linux·编辑器·vim·vi·neovim·lazyvim
Bruce_Liuxiaowei21 分钟前
Linux系统提权之计划任务(Cron Jobs)提权
linux·运维·服务器·网络安全·系统安全
czhc114007566330 分钟前
Linux 96 shell:expect { }
linux·运维·服务器
2501_9301247040 分钟前
编辑shell脚本示例练习
linux·服务器·github
焦思懿--19期--工职大1 小时前
VMWare和centOS的安装
linux·运维·centos
那小子、真烦3 小时前
配置阿里云 YUM 源指南
linux·运维
管家婆客服中心4 小时前
管家婆分销ERP A/V系列导出提示加载数据过大的处理方式
linux·服务器·apache
久绊A5 小时前
指定端口-SSH连接的目标(告别 22 端口暴力破解)
linux·网络·ssh
bantinghy9 小时前
Linux系统TCP/IP网络参数优化
linux·网络·tcp/ip