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;

}

运行结果展示

相关推荐
apocelipes2 小时前
Linux c 运行时获取动态库所在路径
linux·c语言·linux编程
努力学习的小廉2 小时前
深入了解linux系统—— 进程池
linux·运维·服务器
秃头菜狗3 小时前
各个主要目录的功能 / Linux 常见指令
linux·运维·服务器
2301_793102493 小时前
Linux——MySql数据库
linux·数据库
jiunian_cn4 小时前
【Linux】centos软件安装
linux·运维·centos
程序员JerrySUN4 小时前
[特殊字符] 深入理解 Linux 内核进程管理:架构、核心函数与调度机制
java·linux·架构
孤寂大仙v4 小时前
【计算机网络】非阻塞IO——select实现多路转接
linux·计算机网络
派阿喵搞电子5 小时前
Ubuntu下有关UDP网络通信的指令
linux·服务器·网络
Evan_ZGYF丶5 小时前
【PCIe总线】 -- PCI、PCIe相关实现
linux·嵌入式·pcie·pci
舰长1155 小时前
Ubuntu挂载本地镜像源(像CentOS 一样挂载本地镜像源)
linux·ubuntu·centos