【进程间通信】(二)消息队列
1、概念“消息队列”是在消息的传输过程中保存消息的容器,是消息的链接表,存放于内核中,一个消息队列由一个标识符(队列ID)进行表示。2、特点(1)消息队列独立于发送和接收进程, 进程终止时,消息队列极其内容不会被删除。(2)消息队列时面向记录的,其中的消息具有特定的格式和优先级。(3)消息队列可以实现消息的随机查询,不一定要按消息先进先出的原则获取,可按照消息的类型进行获取。3、核心API#inc
·
1、概念
“消息队列”是在消息的传输过程中保存消息的容器,是消息的链接表,存放于内核中,一个消息队列由一个标识符(队列ID)进行表示。
2、特点
(1)消息队列独立于发送和接收进程, 进程终止时,消息队列极其内容不会被删除。
(2)消息队列时面向记录的,其中的消息具有特定的格式和优先级。
(3)消息队列可以实现消息的随机查询,不一定要按消息先进先出的原则获取,可按照消息的类型进行获取。
3、核心API
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
//1、生成键值,成功返回键值(自定义ID值(十六进制)+路径索引值(十六进制)),失败返回-1
key_t ftok(const char *pathname, int proj_id);
//2、创建消息队列,成功返回消息队列ID,失败返回-1。
//int msgget(消息队列键值, 消息标志位(IPC_CREAT, IPC_EXCL));
int msgget(key_t key, int msgflg);
//3、向消息队列发送消息,成功返回获取到的消息结构体mtext的大小,失败返回-1。
//size_t msgrcv(消息队列ID, 消息缓冲区, 消息大小, 消息大小,消息标志位(默认为0));
size_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg);
//4、获取消息队列的消息,成功返回所发送消息结构体中mtext的大小,失败返回-1。
//int msgsnd(消息队列ID, 消息缓冲区, 消息大小, 消息标志位(默认为0));
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
4、例程
4.1 获取消息队列的消息
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <fcntl.h>
//1、建立消息队列数据结构体类型
typedef struct msgque{
long mtype; //消息类型
char mtext[128]; //消息内容
}MSGQUE;
int main()
{
//2、定义消息队列实例,并且初始化
MSGQUE read_msgQue; //用于存放从消息队列中获取到的内容
//3、调用ftok()生成键值
key_t key = ftok("./", 'z');
if(key == -1)
{
perror("create key failed!why:");
exit(0);
}
//4、调用msgget()函数获取消息队列以及队列ID
int msgID = msgget(key, IPC_CREAT|0777);
if(msgID == -1)
{
perror("get message queue failed!why:");
exit(0);
}else{
printf("get message queeue successfully!\n");
}
//5、调用msgrcv()函数获取消息队列的消息
printf("watting message......\n");
if(msgrcv(msgID, &read_msgQue, sizeof(read_msgQue.mtext), 888, 0) == -1)
{
perror("receive failed!why:");
}else{
printf("receive:%s\n", read_msgQue.mtext);
}
exit(0);
}
4.2 向消息队列加入消息
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <fcntl.h>
//1、建立消息队列数据结构体类型
typedef struct msgque{
long mtype; //消息类型
char mtext[128]; //消息内容
}MSGQUE;
int main()
{
//2、定义消息队列实例,并且初始化
MSGQUE send_msgQue = {888, "hello, have you received my message."};
//3、调用msgget()函数获取消息队列以及队列ID
int msgID = msgget(0x1234, IPC_CREAT|0777);
if(msgID == -1)
{
perror("get message queue failed!why:");
}else{
printf("get message queeue successfully!\n");
}
//4、调用msgsnd()函数向消息队列发送消息
msgsnd(msgID, &send_msgQue, sizeof(send_msgQue.mtext), 0);
printf("send_buf:%s\n", send_msgQue.mtext);
exit(0);
}
更多推荐
已为社区贡献1条内容
所有评论(0)