Posix消息队列
每个消息队列有一个保存其当前打开着描述符数的引用计数器;
Posix消息队列至少具备随内核的持续性,这就是说,即使当前没有进程打开着某个消息队列,
该队列及其上的各个消息也将一直存在,直到调用mq_unlink并让它的引用计数到0以删除该队列为止。
每个消息队列有四个属性:
1 2 3 4 5 6 | struct mq_attr { long mq_flags; /*message queue flag: 0, O_NONBLOCK*/ long mq_maxmsg; /*max number of messages allowed on queue*/ long mq_msgsize; /*max size of a message(int bytes)*/ long mq_curmsgs; /*number of messages currently on queue*/ }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <mqueue.h> const int maxline=4096; int main( int argc, char **argv) { int c, flags; char errbuff[maxline]; mqd_t mqd; flags=O_RDWR | O_CREAT; while ((c=getopt(argc, argv, "e" ))!=-1) { switch (c) { case 'e' : flags|=O_EXCL; break ; } } if (optind != argc-1) { fprintf (stderr, "mqcreate [-e] <name>\n" ); exit (-1); } printf ( "optind: %d, %s\n" , optind, argv[optind]); if ((mqd=mq_open(argv[optind], flags, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH, NULL))<0) { strerror_r( errno , errbuff, maxline); fprintf (stderr, "mq_open error: %s\n" , errbuff); exit (-1); } mq_close(mqd); exit (0); } |
消息队列创建的位置默认在/dev/mqueue/
1 2 3 4 5 6 7 8 | $ ./a.out -e /test optind: 2, /test $ cd /dev/mqueue/ $ ls -l total 0 -rw-r--r--. 1 dmin dmin 80 Oct 11 11:23 test $ cat test QSIZE:0 NOTIFY:0 SIGNO:0 NOTIFY_PID:0 |
获取消息队列属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <mqueue.h> int main( int argc, char **argv) { mqd_t mqd; struct mq_attr attr; if (argc!=2) { fprintf (stderr, "usage: ./a.out <name>\n" ); exit (-1); } 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); } |
结果如下:
1 2 | $ ./mqgetattr /test max #msgs=10, max #bytes/msg=8192, #currently on queue=0 |
分类:
UNIX Sockets API
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现