Linux进程间通信---消息队列

1. 消息队列

消息队列就是一个链表, 存于内核之中

特点 :

  • 具有特定的格式以及优先级
  • 消息读取之后, 仍然存在消息队列中 (不同于管道通信)
  • 实现消息的随机查询, 可以按照类型查询
  • 可以实现双方互相通讯(不同于管道通信)

相关API函数 :

#include <sys/msg.h>
//创建/获取消息队列  成功返回id  失败-1
int msgget(key_t key, int msgflg);
//第一个参数: 索引值,以此来查找队列; 第二个参数:打开方式,一般设置为 IPC_CREAT|0777

//发送消息  成功返回0 失败返回-1
int msgsnd(int msgId, const void *msgp, size_t msgsz, int msgflg);
//第一个参数: 消息队列id号,第二个参数:要发送的内容, 
//第三个参数: 发送消息的大小,第四个参数通常采用默认方式,即设置为0

//接收消息
ssize_t msgrcv(int msgId, void* msgp, size_t msgsz, long msqtyp, int msgflg);
//第二个参数:读取消息的缓存区, 第三个参数:缓存区的大小, 
//第四个参数:消息的类型(一般为整型),第五个参数通常采用默认接收方式,即设置为0

//控制消息队列,一般用于删除  成功返回0 失败返回-1
int msgctl(int msgid, int cmd, struct msgid_ds *buf);
//第二个参数: 常用模式为 IPC_RMID(移除创建的队列), 

注: 确定key值时,通常采用 ftok() 函数进行确定, 并且在使用 msgsnd()和msgget() 函数时应线构造一个结构体

//key值的确定
#include <sys/types.h>
#include <sys/ipc.h>

key_t ftok(const char *pathname, int proj_id);
//第一个参数: 指定的文件名  第二个参数: 子序号, 通常取 1-255整型数

//msgsnd()和msgget() 函数时应线构造一个结构体
struct msgbuf
{
	long mtype;
	char mtext[128];
};

具体实例代码 :
①从队列获取信息

#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()
{
	int msgId;
	struct msgbuf readBuf;	

	key_t key;
	key = ftok(".", 1);                     //通过ftok()获取key值

	msgId = msgget(key, IPC_CREAT|0777);    //创建/获取消息队列的id号
	if(msgId == -1)                         //判断是否获取成功
	{
		printf("get que failure\n");	
	}	

	//从消息队列中获取信息  
	msgrcv(msgId, &readBuf, sizeof(readBuf.mtext),888,0);  //888表示消息队列的信号, 0表示默认读取方式
	printf("get message: %s from que\n",readBuf.mtext);

	//获取信息后,进行反馈,也就是可以写信息到队列
	struct msgbuf sendBuf = {999,"thank you"};
	msgsnd(msgId, &sendBuf, strlen(sendBuf.mtext),0);
	
	msgctl(msgId, IPC_RMID, NULL);   //删除创建的队列,防占用内存

	return 0;
}

②发送信息到队列

#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()
{
	int msgId;
	struct msgbuf sendBuf = {888, "hello world"};	//定义发送的类型以及内容

	key_t key;
	key = ftok(".", 1);                             //通过ftok()获取key值

	msgId = msgget(key, IPC_CREAT|0777);
	if(msgId == -1)
	{
		printf("get que failure\n");	
	}	

	//发送信息到队列
	msgsnd(msgId, &sendBuf, strlen(sendBuf.mtext),0);  //0表示默认不堵塞
	
	//定义readBuf 进行接收来自队列的反馈信息
	struct msgbuf readBuf;

	msgrcv(msgId, &readBuf, sizeof(readBuf.mtext),999,0); //999要和上端代码一致
	printf("return  %s from que\n",readBuf.mtext);
	
	msgctl(msgId, IPC_RMID, NULL);

	return 0;
}

两段代码可以实现不同进程间的通信,而且可以满足相互通讯(即可以进行反馈以及接收反馈)
注: 发送信息和读取信息时,应保证 key 值相同, 以及消息类型 type 相同

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值