消息队列学习

1、  创建和打开消息队列

1.1   头文件

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/msg.h>

1.2   功能描述

创建或打开消息队列

1.3   函数原型

int msgget(key_t key,int msgflg)

 

1.4   返回值

成功:返回消息队列的id.

    失败:返回-1

1.5   参数说明

Key:键值   

Msgflag:打开标志。IPC_CREAT:如果不存在则创建

2、  数据发送

2.1 头文件

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/msg.h>

2.2 功能描述

发送消息到消息队列

2.3 函数原型

int msgsnd(int msqid,const void*msgp,size_t msgsz,int msgflg)

2.4 返回值

失败:返回-1

成功:0

2.5 参数说明

Msqid:消息队列的id

Msgp:指向要发送的消息

Msgsz:消息的长度

Msgflg:标志位

3、  从消息队列中读出消息

3.1 头文件

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/msg.h>

 

3.2 功能描述

从消息队列中获取一条消息

3.3 函数原型

Ssize_t msgrcv(int msqid,void *msgp,size_tmsgsz,long msgtyp,int msgflg)

3.4 返回值

成功:返回实际接收到的消息的数据长度

失败:-1

 

3.5 参数说明

Msqid:消息队列的id

Msgp:存放取出的消息

Msgsz:希望取到的消息的最大长度

Msgtyp:消息的类型,0:忽略类型,直接取消息队列中第一条消息,>0:取消息队列中类型等于msgtype的第一条消息,<0:取类型比msgtyp的绝对值要小或者等于的消息,如果有多条消息满足该条件,则取类型最小的那条。

Msgflg:标志

 

4、  删除消息队列

4.1 头文件

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/msg.h>

 

4.2 功能描述

控制消息队列

 

4.3 函数原型

int msgctl(int msqid,int cmd,structmsqid_ds *buf)

 

4.4 返回值

成功:0

失败:-1

4.5 参数说明

Msqid:消息队列的id

Cmd:对消息队列执行的命令,IPC_RMID为删除消息队列

Buf:获取内核中msqid_ds结构

send.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>

struct msgs
{
	char msgtype;
	char message[500];
};

void main()
{
	
	int msgid;
	int res;
	char type;
	char message[500];
	struct msgs msg; 

	//创建消息队列
	msgid =  msgget(1234,IPC_CREAT);
	
	while(1)
	{
		//获取消息类型
		printf("please input message type,type not 0\n");
		scanf("%d",&type);
		
		//如果用户输入的消息类型为0,退出循环		
		if(type == 0)
		{
			return;
		}		
		printf("please input message frame\n");
		scanf("%s",message);
		
		msg.msgtype = type;
		strcpy(msg.message,message);
		
		res = msgsnd(msgid,&msg,sizeof(struct msgs),0);
		if(res < 0)
		{
			printf("message send error !!!\n");
		}
	}
	
	msgctl(msgid,IPC_RMID,0);
	
}

recv.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>

struct msgs
{
	char msgtype;
	char message[500];
};

void main()
{
	
	int msgid;
	int res;
	char type;
	char message[500];
	struct msgs msg; 

	//创建消息队列
	msgid =  msgget(1234,IPC_EXCL);
	
	while(1)
	{
        res = msgrcv(msgid,&msg,sizeof(struct msgs),0,0);				
		if(res > 0)
		{
			printf("recv message %s\n",msg.message);
		}
	}
	
	msgctl(msgid,IPC_RMID,0);
	
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值