您的位置:首页 > 其它

Unix IPC之Posix消息队列(3)

2015-08-13 21:04 316 查看
// mqreveive.c

#include    "unpipc.h"

int
main(int argc, char **argv)
{
int     c, flags;
mqd_t   mqd;
ssize_t n;
unsigned int prio;
void    *buff;
struct mq_attr  attr;

flags = O_RDONLY;
while ( (c = Getopt(argc, argv, "n")) != -1)
{
switch (c)
{
case 'n': // 命令行中带-n表示以非阻塞模式
flags |= O_NONBLOCK;
break;
}
}
if (optind != argc - 1)
err_quit("usage: mqreceive [ -n ] <name>");

mqd = Mq_open(argv[optind], flags);
Mq_getattr(mqd, &attr);
// 这里开辟的缓冲区需要>=消息的最大长度,以便能够容纳接收到的消息
buff = Malloc(attr.mq_msgsize); // 根据最大消息的大小开辟缓冲区以接收消息

n = Mq_receive(mqd, buff, attr.mq_msgsize, &prio); // 这里的len长度需要>=消息的最大长度,否则mq_receive会立即返回EMSGSIZE错误
printf("read %ld bytes, priority = %u\n", (long) n, prio);

exit(0);
}


View Code

运行结果:

[dell@localhost pxmsg]$ ls -l /tmp/mqueue/
总用量 0
[dell@localhost pxmsg]$ ./mqcreate1 /msgqueue
[dell@localhost pxmsg]$ ls -l /tmp/mqueue/
总用量 0

[dell@localhost pxmsg]$ sudo mount -t mqueue none /tmp/mqueue
[sudo] password for dell:
[dell@localhost pxmsg]$ ls -l /tmp/mqueue/
总用量 0
-rw-r--r--. 1 dell dell 80 8月  13 20:52 msgqueue

[dell@localhost pxmsg]$ ./mqsend /msgqueue 10 1
[dell@localhost pxmsg]$ ./mqsend /msgqueue 20 2
[dell@localhost pxmsg]$ ./mqsend /msgqueue 30 3
[dell@localhost pxmsg]$ ls -l /tmp/mqueue/
总用量 0
-rw-r--r--. 1 dell dell 80 8月  13 20:55 msgqueue

[dell@localhost pxmsg]$ ./mqreceive /msgqueue
read 30 bytes, priority = 3
[dell@localhost pxmsg]$ ./mqreceive /msgqueue
read 20 bytes, priority = 2
[dell@localhost pxmsg]$ ./mqreceive /msgqueue
read 10 bytes, priority = 1
[dell@localhost pxmsg]$ ./mqreceive /msgqueue
^C
// 这里默认是阻塞方式,当消息队列为空时将会被阻塞,所以下面我们使用非阻塞方式。
[dell@localhost pxmsg]$ ./mqreceive -n /msgqueue
mq_receive error: Resource temporarily unavailable
[dell@localhost pxmsg]$
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: