消息队列
查看消息队列的信息
cat /proc/sys/kernel/msgmax
cat /proc/sys/kernel/msgmnb
cat /proc/sys/kernel/msgmni
IPC对象数据结构:
消息队列在内核中的表示
消息对列函数
msgget函数
删除消息队列可以使用
ipcrm -q msgid(一些数字)
查看消息队列
ipcs
上代码:
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int main()
{
int msgid;
msgid = msgget(1234,0666);
if(msgid == -1)
{
ERR_EXIT("msgget");
}
printf("success");
return 0;
}
显示结果:
因为我的消息队列是没有消息的。
可以使用ipcs查看
如果想要创建成功:
可以修改这行代码:
msgid = msgget(1234,0666 | IPC_CREAT);
结果:
ipcs一下:
在执行一次是打开消息队列。并没有重新创建一个。
msgctl函数
IPC_STAT的用法:
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int main()
{
int msgid;
msgid = msgget(1234,0);//打开消息对列
if(msgid == -1)
{
ERR_EXIT("msgget");
}
printf("success\n");
printf("msgid = %d\n",msgid);
struct msqid_ds buf;
msgctl(msgid,IPC_STAT,&buf);//获取消息对列字段
printf("mode = %o\n",buf.msg_perm.mode);
printf("bytes = %ld\n",buf.msg_cbytes);
printf("number = %d\n",(int)buf.msg_qnum);
printf("msgmax = %d\n",(int)buf.msg_qbytes);
return 0;
}
IPC_SET的用法:
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int main()
{
int msgid;
msgid = msgget(1234,0);//打开消息对列
if(msgid == -1)
{
ERR_EXIT("msgget");
}
printf("success\n");
printf("msgid = %d\n",msgid);
struct msqid_ds buf;
msgctl(msgid,IPC_STAT,&buf);//获取消息队列字段
printf("mode = %o\n",buf.msg_perm.mode);
printf("bytes = %ld\n",buf.msg_cbytes);
printf("number = %d\n",(int)buf.msg_qnum);
printf("msgmax = %d\n",(int)buf.msg_qbytes);
sscanf("200","%o",(unsigned int*)&buf.msg_perm.mode);//修改消息队列权限
msgctl(msgid,IPC_SET,&buf);//设置消息队列字段
printf("mode = %o\n",buf.msg_perm.mode);
printf("bytes = %ld\n",buf.msg_cbytes);
printf("number = %d\n",(int)buf.msg_qnum);
printf("msgmax = %d\n",(int)buf.msg_qbytes);
return 0;
}
运行结果:
msgsnd函数:
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
struct msgbuf{
long mtype;
char mtext[1];
};
int main(int argc,char *argv[])
{
if(argc != 3)
{
fprintf(stderr,"Usage: %s <bytes> <types>\n",argv[0]);
exit(EXIT_FAILURE);
}
int len = atoi(argv[1]);
int type = atoi(argv[2]);
int msgid;
msgid = msgget(1234,0);//打开消息对列
if(msgid == -1)
{
ERR_EXIT("msgget");
}
struct msgbuf *ptr;
ptr = (struct msgbuf*)malloc(sizeof(long) * len);
ptr -> mtype = type;
if(msgsnd(msgid,ptr,len,0) < 0)
{
ERR_EXIT("msgsnd");
}
return 0;
}
执行上一个函数查看消息队列的信息:
msgrcv函数
消息对列实现回射客户/服务器