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]$
相关文章推荐
- CF558E - A Simple Task线段树
- 黑马程序员——Java基础--编程基础(2)
- 移动端图片超过屏幕宽度处理办法
- EXCEL工作表保护密码忘记了,如何撤消工作表保护?
- hpu-1690-CZY的组合数烦恼
- NYOJ-背包问题(贪心)
- 浅谈动态注册JNI方法
- zoj 1203 Swordfish
- iOS基础-UIKit框架-多控制器管理-UINavigationController、控制器的生命周期
- 企业级服务器设计与实现经验之插件系统基础篇
- zoj1942Frogger
- [leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
- 求回文数
- 拓扑排序 HDU 3342 Legal or Not
- 引用
- 菜鸟学前端之初入江湖
- android学习笔记NO.5
- TCP的状态兼谈Close_Wait和Time_Wait的状态
- 【HDOJ 5384】Danganronpa
- ssh的755和644