您的位置:首页 > 其它

Unix IPC之Posix消息队列(2)

2015-08-12 21:33 369 查看
/* 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);
}


运行结果:

[dell@localhost pxmsg]$ ./mqcreate1 /hello.1234
[dell@localhost pxmsg]$ ./mqgetattr /hello.1234
max #msgs = 10, max #bytes/msg = 8192, #currently on queue = 0
[dell@localhost pxmsg]$


[dell@localhost 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);
}


View Code
运行结果:

[dell@localhost pxmsg]$ cat /proc/sys/fs/mqueue/msg_max
10
[dell@localhost pxmsg]$ cat /proc/sys/fs/mqueue/msgsize_max
8192
[dell@localhost pxmsg]$ ./mqcreate -m 5 -z 512 /hello.123
[dell@localhost pxmsg]$ ./mqgetattr /hello.123
max #msgs = 5, max #bytes/msg = 512, #currently on queue = 0
[dell@localhost pxmsg]$ ls -l /tmp/mqueue/hello.123
-rw-r--r--. 1 dell dell 80 8月  12 21:26 /tmp/mqueue/hello.123
[dell@localhost pxmsg]$


说明:这里设置时不能超过系统设定的参数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: