/* Query status and attributes of message queue MQDES. */ extern int mq_getattr (mqd_t __mqdes, struct mq_attr *__mqstat) __THROW __nonnull ((2)); /* Set attributes associated with message queue MQDES and if OMQSTAT is not NULL also query its old attributes. */ extern int mq_setattr (mqd_t __mqdes, __const struct mq_attr *__restrict __mqstat, struct mq_attr *__restrict __omqstat) __THROW __nonnull ((2));
struct mq_attr { long mq_flags; /* message queue flags */ long mq_maxmsg; /* maximum number of messages */ long mq_msgsize; /* maximum message size */ long mq_curmsgs; /* number of messages currently queued */ long __reserved[4]; /* ignored for input, zeroed for output */ };
程序1(mqgetattr.c):获取一个消息队列的默认属性。(以大写开头的函数都是对应函数的包裹函数,仅仅在里面添加了出错信息)
// mqgetattr.c #include "unpipc.h" int main(int argc, char **argv) { mqd_t mqd; struct mq_attr attr; if (argc != 2) err_quit("usage: mqgetattr <name>"); mqd = Mq_open(argv[1], O_RDONLY); Mq_getattr(mqd, &attr); printf("max #msgs = %ld, max #bytes/msg = %ld, " "#currently on queue = %ld\n", attr.mq_maxmsg, attr.mq_msgsize, attr.mq_curmsgs); Mq_close(mqd); exit(0); }
运行结果:
[[email protected] pxmsg]$ ./mqcreate1 /hello.1234 [[email protected] pxmsg]$ ./mqgetattr /hello.1234 max #msgs = 10, max #bytes/msg = 8192, #currently on queue = 0 [[email protected] pxmsg]$
[[email protected] pxmsg]$ ls -l /tmp/mqueue/hello.1234 -rw-r--r--. 1 dell dell 80 8月 12 21:03 /tmp/mqueue/hello.1234
即:80KB = 10 * 8192B
程序2:指定消息队列的最大消息个数及每个消息的最大长度。
#include "unpipc.h" struct mq_attr attr; /* mq_maxmsg and mq_msgsize both init to 0 */ int main(int argc, char **argv) { int c, flags; mqd_t mqd; flags = O_RDWR | O_CREAT; while ( (c = Getopt(argc, argv, "em:z:")) != -1) { switch (c) { case ‘e‘: flags |= O_EXCL; break; case ‘m‘: attr.mq_maxmsg = atol(optarg); break; case ‘z‘: attr.mq_msgsize = atol(optarg); break; } } if (optind != argc - 1) err_quit("usage: mqcreate [ -e ] [ -m maxmsg -z msgsize ] <name>"); if ((attr.mq_maxmsg != 0 && attr.mq_msgsize == 0) || (attr.mq_maxmsg == 0 && attr.mq_msgsize != 0)) err_quit("must specify both -m maxmsg and -z msgsize"); mqd = Mq_open(argv[optind], flags, FILE_MODE, (attr.mq_maxmsg != 0) ? &attr : NULL); Mq_close(mqd); exit(0); }
运行结果:
[[email protected] pxmsg]$ cat /proc/sys/fs/mqueue/msg_max 10 [[email protected] pxmsg]$ cat /proc/sys/fs/mqueue/msgsize_max 8192 [[email protected] pxmsg]$ ./mqcreate -m 5 -z 512 /hello.123 [[email protected] pxmsg]$ ./mqgetattr /hello.123 max #msgs = 5, max #bytes/msg = 512, #currently on queue = 0 [[email protected] pxmsg]$ ls -l /tmp/mqueue/hello.123 -rw-r--r--. 1 dell dell 80 8月 12 21:26 /tmp/mqueue/hello.123 [[email protected] pxmsg]$
说明:这里设置时不能超过系统设定的参数。
时间: 2024-10-20 16:18:24