消息队列
消息队列(message queue):不在磁盘上,没有文件名,有一个关键字key可以打开消息队列,消息队列中有很多通道,专门用来写入/读取信息的。
创建/打开消息队列
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgget(key_t key, int msgflg); //创建或者打开消息队列
//参数一:自己指定的关键字key的编号
//参数二:标志位,如果是创建消息队列则 O_CREAT | 权限
//例如:msgget(1234, IPC_CREAT|0644);
//如果是打开某一个消息队列,则第二个参数为0
//创建成功返回值是消息队列的id,-1代表出错
示例程序:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int main( void ) {
int id = msgget(1234, IPC_CREAT|0644);
if ( id == -1 )
perror("msgget"),exit(1);
printf("create ok %d\n",id);
}
ipcs -q //查看系统中的消息队列
ipcrm -Q key //手动删除指定的消息队列
给消息队列写入数据:
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
//参数一,要写入的消息队列的id
//参数二,消息内容,需要自己定义一个指定的结构体
//参数三,消息的大小,只算结构体的消息数据的大小
//参数四,标志位,一般写0,如果想要非阻塞的话写 IPC_NOWAIT
//这个就是参数二的结构体了
struct msgbuf {
long mtype; /* 指定消息队列的通道, 一般>0,=0代表任何通道 */
char mtext[1]; /*消息数据 */
};
示例程序:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf{
long channel;
char buf[100];
};
int main( void ) {
//打开消息队列(消息队列需要先被创建)
int id = msgget(1234, 0);
if ( id == -1 )
perror("msgget"),exit(1);
//创建msgbuf结构体
struct msgbuf mb;
memset(&mb, 0x00, sizeof(mb));
printf("channel:");
//指定几号通道
scanf("%d%*c", &mb.channel);
printf("msg:");
//写入数据(这里只是实验,所以只读取100个字节)
fgets(mb.buf, 100, stdin);
//向消息队列中发送数据
if ( msgsnd(id, &mb, strlen(mb.buf), IPC_NOWAIT) == -1 )
perror("msgsnd"),exit(1);
}
从消息队列获取数据
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz,
long msgtyp, int msgflg);
//参数一:指定消息队列id
//参数二:装获取到的数据的结构体
//参数三:参数二装数据的大小
//参数四:指定从哪个消息通道获取
//参数五:标志位,一般写0,如果想要非阻塞的话写 IPC_NOWAIT
示例程序:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf{
long channel;
char buf[100];
};
int main( void ) {
int id = msgget(1234, 0);
if ( id == -1 )
perror("msgget"),exit(1);
//存放数据的结构体
struct msgbuf mb;
memset(&mb, 0x00, sizeof(mb));
long type;
printf("channel:");
//指定通道
scanf("%d", &type);
//从指定通道获取数据
msgrcv(id, &mb, 100, type, IPC_NOWAIT);
printf("[%s]\n", mb.buf);
}
关闭消息队列
手动关闭:
ipcrm -Q key
也可以使用函数进行关闭
msgctl(id, IPC_RMID, 0);
消息队列的大小相关
cat /proc/sys/kernel/msgmax
//得到消息队列的某一个通道的一个消息的最大字节
cat /proc/sys/kernel/msgmnb
//得到一个消息队列的最大字节
cat /proc/sys/kernel/msgmni
//得到系统中对多容纳多少消息队列