151-消息队列

分为添加消息,读取消息两个动作
消息是一个结构体。第一个成员是类型。
151-消息队列_第1张图片
发送消息,需要设置消息类型。读取的时候要指定消息类型
151-消息队列_第2张图片
如:1号消息,2号消息

消息的方法

#include 
#include 
#include 

/*
msgget()创建或者获取一个消息队列
msgget()成功返回消息队列 ID,失败返回-1
msqflg: IPC_CREAT
*/
int msgget(key_t key, int msqflg); 


/*
msgsnd()发送一条消息,消息结构为:
struct msgbuf
{
long mtype; // 消息类型, 必须大于 0
char mtext[1]; // 消息数据
};
msgsnd()成功返回 0, 失败返回-1
msqsz: 指定 mtext 中有效数据的长度
msqflg:一般设置为 0 可以设置 IPC_NOWAIT
*/
int msgsnd(int msqid, const void *msqp, size_t msqsz, int msqflg); 


/*
msgrcv()接收一条消息
msgrcv()成功返回 mtext 中接收到的数据长度, 失败返回-1
msqtyp: 指定接收的消息类型,类型可以为 0
msqflg: 一般设置为 0 可以设置 IPC_NOWAIT
*/
ssize_t msgrcv(int msqid, void *msgp, size_t msqsz, long msqtyp, int msqflg); 


/*
msgctl()控制消息队列
msgctl()成功返回 0,失败返回-1
cmd: IPC_RMID
*/
int msgctl(int msqid, int cmd, struct msqid_ds *buf);

消息添加满了也会阻塞住
151-消息队列_第3张图片

进程 a 发送一条消息,进程 b 读取消息

vi a.c

#include 
#include 
#include 
#include 
#include 
#include 

typedef struct msgdata//定义消息
{
     
	long mtype;//类型
	char buff[128];
}MsgData;

int main()
{
     
	int msgid = msgget((key_t)1234, 0664 | IPC_CREAT);
	assert(msgid != -1);

	MsgData data;
	memset(&data, 0, sizeof(data));
	data.mtype = 1;// >=1
	strcpy(data.buff, "hello1");

	msgsnd(msgid, &data, 128, 0);//给数据的大小:128
	exit(0);
}

151-消息队列_第4张图片

vi b.c

#include 
#include 
#include 
#include 
#include 
#include 

typedef struct msgdata
{
     
	long mtype;
	char buff[128];
}MsgData;

int main()
{
     
	int msgid = msgget((key_t)1234, 0664 | IPC_CREAT);
	assert(msgid != -1);

	MsgData data;
	memset(&data, 0, sizeof(data));

	msgrcv(msgid, &data, 128, 1, 0);
	printf("data.type: %d\n", data.mtype);
	printf("data.text: %s\n", data.buff);

	msgctl(msgid, IPC_RMID, NULL);
	exit(0);
}

151-消息队列_第5张图片
运行结果如下:
151-消息队列_第6张图片
如果读取2号类型消息
151-消息队列_第7张图片
阻塞住了,因为没有2号类型消息
可以添加2号类型消息来解决阻塞情况

消息类型要>=1,因为0有特殊的意义
如果置为0
那么系统就不会区分消息类型了,有消息就可以读了

消息队列为空或者满,运行程序,自动阻塞
151-消息队列_第8张图片

你可能感兴趣的:(Linux的学习,linux)