消息队列
管道: 不能读取特定,只要管道中有数据,就会全部读取 消息队列: 可以读取相对应的数据
1. 根据key值申请消息队列ID号 --> msgget() --> man 2 msgget
功能: msgget - get a message queue identifier //获取消息队列的ID号
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgget(key_t key, int msgflg);
key: 消息队列对应的key值
msgflg: IPC_CREAT|0666: 不存在则创建
IPC_EXCL: 存在就会报错
The execute permissions are not used
返回值:
成功:消息队列ID号
失败:-1
2. 发送消息到消息队列 – msgsnd() --> man 2 msgsnd
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
msqid: 消息队列的ID号
msgp:发送到消息队列的数据缓冲区,类型必须是
struct msgbuf {
long mtype; //数据的标志
char mtext[1]; //数据的正文
};
msgsz: 就是struct msgbuf中的mtext的大小
msgflg:一般为普通属性,填0
返回值:
成功:0
失败: -1
3. 接收消息队列数据 – msgrcv —> man 2 msgrcv
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
msqid: 消息队列的ID号
msgp:接收消息的数据缓冲区,类型必须是
struct msgbuf {
long mtype; //数据的标志
char mtext[1]; //数据的正文
};
msgsz: 就是struct msgbuf中的mtext的大小
msgtyp:消息的类型
msgflg:一般为普通属性,填0
返回值:
成功: 接受到正文的字节数
失败: -1
4. 设置消息队列的属性(删除消息队列) — msgctl() — man 2 msgctl
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
msqid: 消息队列的ID号
cmd: 操作命令字 IPC_RMID --> 删除消息队列
buf: 删除 --> NULL
返回值:
成功: 0
失败: -1
发送端示例代码
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
//定义消息的结构体
struct msgbuf{
long mtype;
char mtext[50];
};
int main()
{
key_t key;
int msgid,ret;
//0. 定义消息变量,并且赋值
struct msgbuf buf;
buf.mtype = 10;
bzero(&(buf.mtext),50);
strcpy(buf.mtext,"hello");
//1. 获取key值
key = ftok(".",10);
printf("key = %d\n",key);
//2. 根据key值申请ID号
msgid = msgget(key,IPC_CREAT | 0666);
printf("msgid : %d\n",msgid);
//3. 发送数据到消息队列中
ret = msgsnd(msgid,&buf,strlen(buf.mtext),0);
if(ret == -1)
{
printf("msgsnd error!\n");
exit(1);
}
return 0;
}
接收端示例代码
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
//定义消息的结构体
struct msgbuf{
long mtype;
char mtext[50];
};
int main()
{
key_t key;
int msgid;
int ret;
struct msgbuf buf;
bzero((&buf.mtext),50);
//1. 获取key值
key = ftok(".",10);
printf("key = %d\n",key);
//2. 根据key值申请ID号
msgid = msgget(key,IPC_CREAT | 0666);
printf("msgid : %d\n",msgid);
ret = msgrcv(msgid,&buf,sizeof(buf.mtext),10,0);
if(ret < 0)
{
printf("msgrcv error!\n");
}
printf("buf.mtext = %s\n",buf.mtext);
//3. 删除消息队列
msgctl(msgid,IPC_RMID,NULL);
return 0;
}