找回密码
 注册
关于网站域名变更的通知
查看: 511|回复: 1
打印 上一主题 下一主题

Linux进程通信之POSIX消息队列

[复制链接]

该用户从未签到

跳转到指定楼层
1#
发表于 2021-4-26 10:57 | 只看该作者 |只看大图 回帖奖励 |正序浏览 |阅读模式

EDA365欢迎您登录!

您需要 登录 才可以下载或查看,没有帐号?注册

x

/ O) h, n3 c7 k消息队列是Linux IPC中很常用的一种通信方式,它通常用来在不同进程间发送特定格式的消息数据。) s- H  }; X3 I

& p# K& ]' m  w+ \8 i+ Y消息队列和之前讨论过的管道和FIFO有很大的区别,主要有以下两点:- Z- Q/ r1 i9 F1 x; A2 t" w
% m' B! I) w/ j  ?
  • 一个进程向消息队列写入消息之前,并不需要某个进程在该队列上等待该消息的到达,而管道和FIFO是相反的,进程向其中写消息时,管道和FIFO必需已经打开来读,那么内核会产生SIGPIPE信号(感谢shanshan_fangfang的指正)。
  • IPC的持续性不同。管道和FIFO是随进程的持续性,当管道和FIFO最后一次关闭发生时,仍在管道和FIFO中的数据会被丢弃。消息队列是随内核的持续性,即一个进程向消息队列写入消息后,然后终止,另外一个进程可以在以后某个时刻打开该队列读取消息。只要内核没有重新自举,消息队列没有被删除。( a5 n" d" l) l& h9 L& Y" W8 J

1 t# d2 \; R$ A8 t9 |: c4 X  H" d: _+ o! s  y1 L( W5 r8 F9 i5 ~( o- `6 @
消息队列中的每条消息通常具有以下属性:; V2 A2 M0 ^" r: d" K  X* e4 q* m
: O  f- |# i" V- K$ l/ [' Q' W' x
  • 一个表示优先级的整数;
  • 消息的数据部分的长度;
  • 消息数据本身;: I; e4 ~! |/ |! [1 G4 Y
' z6 D( N! _; E- d! U% k5 t
POSIX消息队列的一个可能的设计是一个如下图所示的消息链表,链表头部有消息队列的属性信息。
  c' j3 D! D) O  i( G/ L
) Y: p5 h2 c9 r$ N) B 9 C. Q6 ~4 a0 s% j& q

. L! \% z7 V; E图1消息队列的可能布局* [1 }+ _1 ]& s+ z

' c; x9 Z0 \5 F" L1 POSIX消息队列的创建和关闭# `2 i1 ^. ^6 V7 @. E
POSIX消息队列的创建,关闭和删除用到以下三个函数接口:
  y; \* y. l: b9 v( U" \0 b, H' w+ m  m# J- W  p: ^
  • #include <mqueue.h>
  • mqd_t mq_open(const char *name, int oflag, /* mode_t mode, struct mq_attr *attr */);
  •                        //成功返回消息队列描述符,失败返回-1
  • mqd_t mq_close(mqd_t mqdes);
  • mqd_t mq_unlink(const char *name);
  •                            //成功返回0,失败返回-12 {+ ]; r( t& o% p1 k
  S7 e# `: W& G+ R! ^5 ~8 t9 ]
+ \2 p7 i+ H% `- x( U7 h
mq_open用于打开或创建一个消息队列。
! [/ v, H3 x# ^4 `# Zname:表示消息队列的名字,它符合POSIX IPC的名字规则。5 p- F7 D6 i1 g+ r$ ?
1 v- X3 l" A2 u$ R) `5 o; p- S( c% ?
oflag:表示打开的方式,和open函数的类似。有必须的选项:O_RDONLY,O_WRONLY,O_RDWR,还有可选的选项:O_NONBLOCK,O_CREAT,O_EXCL。
( c# [' T: f6 C; Z+ r. w/ C, O7 ]
. Y3 C9 d' b  x; G' K% E0 Z+ _$ {mode:是一个可选参数,在oflag中含有O_CREAT标志且消息队列不存在时,才需要提供该参数。表示默认访问权限。可以参考open。
2 B7 n% q: @6 ^: {' A3 r0 [4 k
  h) M  f% r7 \+ Y: O0 n! yattr:也是一个可选参数,在oflag中含有O_CREAT标志且消息队列不存在时才需要。该参数用于给新队列设定某些属性,如果是空指针,那么就采用默认属性。" Z/ L# L7 Z! d7 ^* P

. q8 c& Q( a9 o/ l5 P* Tmq_open返回值是mqd_t类型的值,被称为消息队列描述符。在Linux 2.6.18中该类型的定义为整型:
1 z5 s/ T+ g7 z) S, |2 e  _
" g# m' o$ R' y+ j% `6 W
  • #include <bits/mqueue.h>
  • typedef int mqd_t;: ^' ]* g; _0 p& ?' m

+ M, \& i/ F8 b* x1 T) z; J6 B1 w- z
, @) I* ^, f8 |0 jmq_close用于关闭一个消息队列,和文件的close类型,关闭后,消息队列并不从系统中删除。一个进程结束,会自动调用关闭打开着的消息队列。$ y' m+ K, x3 M1 v6 h9 U7 u, t# M5 c; Z
& ^  r( C, E4 R: t" M" V
mq_unlink用于删除一个消息队列。消息队列创建后只有通过调用该函数或者是内核自举才能进行删除。每个消息队列都有一个保存当前打开着描述符数的引用计数器,和文件一样,因此本函数能够实现类似于unlink函数删除一个文件的机制。
9 [6 W! M+ m$ f) B0 H# G; w$ m2 o% p! p- q, j
POSIX消息队列的名字所创建的真正路径名和具体的系统实现有关,关于具体POSIX IPC的名字规则可以参考《UNIX 网络编程 卷2:进程间通信》的P14。6 y6 k; t8 e0 C: ?! I& D
9 f$ I2 ]! t1 Y4 w2 @
经过测试,在Linux 2.6.18中,所创建的POSIX消息队列不会在文件系统中创建真正的路径名。且POSIX的名字只能以一个’/’开头,名字中不能包含其他的’/’。
, K* O- E: ]3 u$ C# s
% q9 @& }/ Y9 U3 E5 L" n) y: l4 e# O2 o' ]$ i; A
2 POSIX消息队列的属性3 @3 q7 c, `! ?3 ^* o0 a- b

( G, F* Z8 K; V: L& r- Z- e8 V/ SPOSIX标准规定消息队列属性mq_attr必须要含有以下四个内容:
5 R9 v! I5 V3 Z7 F: A
5 J: W, n9 I6 W7 @! z" V) ]
  • long    mq_flags //消息队列的标志:0或O_NONBLOCK,用来表示是否阻塞
  • long    mq_maxmsg  //消息队列的最大消息数
  • long    mq_msgsize  //消息队列中每个消息的最大字节数
  • long    mq_curmsgs  //消息队列中当前的消息数目
    , P6 Q' N4 }/ }; |( W, a) m
( v# k0 v( l, Y! K1 S0 G
, y& \! N3 m3 U# I
在Linux 2.6.18中mq_attr结构的定义如下:
" ]* @0 `8 }2 ]& v- _, x: [: e% `( o  g' C0 Y" n
  • #include <bits/mqueue.h>
  • struct mq_attr
  • {
  •   long int mq_flags;      /* Message queue flags.  */
  •   long int mq_maxmsg;   /* Maximum number of messages.  */
  •   long int mq_msgsize;   /* Maximum message size.  */
  •   long int mq_curmsgs;   /* Number of messages currently queued.  */
  •   long int __pad[4];
  • };
    3 o2 n. U/ a* b& ~* e
7 O8 h: P, I  y, M  s& `

$ ?& a- P* [3 d+ _( ~POSIX消息队列的属性设置和获取可以通过下面两个函数实现:
/ x! L7 u/ b; \, \' {/ P% @+ [0 A" _, ^% }. a% P
  • #include <mqueue.h>
  • mqd_t mq_getattr(mqd_t mqdes, struct mq_attr *attr);
  • mqd_t mq_setattr(mqd_t mqdes, struct mq_attr *newattr, struct mq_attr *oldattr);
  •                                //成功返回0,失败返回-1; U+ S% W' M/ Q* f
; w' u; |2 Z7 d: ]% M, k9 @
" E! U/ v+ F/ G5 D( [  j
mq_getattr用于获取当前消息队列的属性,mq_setattr用于设置当前消息队列的属性。其中mq_setattr中的oldattr用于保存修改前的消息队列的属性,可以为空。6 y0 i, a( {( B0 k/ N8 {% W
3 j# i+ F# K+ g7 [$ e
mq_setattr可以设置的属性只有mq_flags,用来设置或清除消息队列的非阻塞标志。newattr结构的其他属性被忽略。mq_maxmsg和mq_msgsize属性只能在创建消息队列时通过mq_open来设置。mq_open只会设置该两个属性,忽略另外两个属性。mq_curmsgs属性只能被获取而不能被设置。: ~- y2 k6 M7 I7 U) o0 J
+ ^! K5 ^) J$ Q$ X& K; d
下面是测试代码:
6 @2 T# Z# c' T3 _  C7 |; [; _
! m3 w8 d, d6 w3 g; D0 D7 V9 M% i& A9 e
  • #include <iostream>
  • #include <cstring>
  • #include <errno.h>
  • #include <unistd.h>
  • #include <fcntl.h>
  • #include <mqueue.h>
  • using namespace std;
  • int main()
  • {
  •     mqd_t mqID;
  •     mqID = mq_open("/anonymQueue", O_RDWR | O_CREAT, 0666, NULL);
  •     if (mqID < 0)
  •     {
  •         cout<<"open message queue error..."<<strerror(errno)<<endl;
  •         return -1;
  •     }
  •     mq_attr mqAttr;
  •     if (mq_getattr(mqID, &mqAttr) < 0)
  •     {
  •         cout<<"get the message queue attribute error"<<endl;
  •         return -1;
  •     }
  •     cout<<"mq_flags:"<<mqAttr.mq_flags<<endl;
  •     cout<<"mq_maxmsg:"<<mqAttr.mq_maxmsg<<endl;
  •     cout<<"mq_msgsize:"<<mqAttr.mq_msgsize<<endl;
  •     cout<<"mq_curmsgs:"<<mqAttr.mq_curmsgs<<endl;
  • }# m) r. _. z$ l3 W8 V1 G

% |( o( [- J, [$ z& m% G
5 N; @9 k/ E( h/ ]4 E& z" I) p+ t      在Linux 2.6.18中执行结果是:0 h0 N( C2 a! |' ?: m9 _6 P8 b

' q/ w* N; p) a, k  Y8 \8 ~. S' n+ [. e
  • mq_flags:0
  • mq_maxmsg:10
  • mq_msgsize:8192
  • mq_curmsgs:0
    # H8 z3 r- x2 w. t) n
* C- _# s& o! B1 O( w+ K

$ V3 W9 D  [5 G* M  H# G- {: q- _3 POSIX消息队列的使用' S- a6 V  h' u( p& r5 `3 [

2 Z, Y! V1 v: i& {. {) VPOSIX消息队列可以通过以下两个函数来进行发送和接收消息:
" ^* n2 O9 N" F7 `% q3 N2 L
! \; H1 |9 s4 M% \4 W
  • #include <mqueue.h>
  • mqd_t mq_send(mqd_t mqdes, const char *msg_ptr,
  •                       size_t msg_len, unsigned msg_prio);
  •                      //成功返回0,出错返回-1
  • mqd_t mq_receive(mqd_t mqdes, char *msg_ptr,
  •                       size_t msg_len, unsigned *msg_prio);
  •                      //成功返回接收到消息的字节数,出错返回-1
  • #ifdef __USE_XOPEN2K
  • mqd_t mq_timedsend(mqd_t mqdes, const char *msg_ptr,
  •                       size_t msg_len, unsigned msg_prio,
  •                       const struct timespec *abs_timeout);
  • mqd_t mq_timedreceive(mqd_t mqdes, char *msg_ptr,
  •                       size_t msg_len, unsigned *msg_prio,
  •                       const struct timespec *abs_timeout);
  • #endif
    + D) p$ l* Y* G+ P+ b/ s* f
. \) y+ x+ c$ t* F! h
( C& f$ I* S; @0 X9 q, O$ p

- ?- \/ g9 [7 K0 Y   mq_send向消息队列中写入一条消息,mq_receive从消息队列中读取一条消息。+ t3 b6 Y/ r$ j+ d  B

2 z! w( ~$ D. L. G/ V1 Gmqdes:消息队列描述符;
( `: j* D6 ^# U7 a# L  c( |' L; b  |
msg_ptr:指向消息体缓冲区的指针;& Z7 f6 P2 z3 q
  e1 P" X: f, O- H3 g% P1 B9 Z, t
msg_len:消息体的长度,其中mq_receive的该参数不能小于能写入队列中消息的最大大小,即一定要大于等于该队列的mq_attr结构中mq_msgsize的大小。如果mq_receive中的msg_len小于该值,就会返回EMSGSIZE错误。POXIS消息队列发送的消息长度可以为0。- p( q% C/ ~4 x& Q

2 j) N# Z& k# E0 Nmsg_prio:消息的优先级;它是一个小于MQ_PRIO_MAX的数,数值越大,优先级越高。POSIX消息队列在调用mq_receive时总是返回队列中最高优先级的最早消息。如果消息不需要设定优先级,那么可以在mq_send是置msg_prio为0,mq_receive的msg_prio置为NULL。8 g5 O" `$ b" S- C0 u# v
5 m  M$ z5 n# u* w, h
还有两个XSI定义的扩展接口限时发送和接收消息的函数:mq_timedsend和mq_timedreceive函数。默认情况下mq_send和mq_receive是阻塞进行调用,可以通过mq_setattr来设置为O_NONBLOCK。
2 R/ j1 w9 G5 G+ Q6 [1 h
. {5 P3 b+ X/ P" K* r% f4 s2 K6 q2 w% U
3 \7 V+ h+ e8 h: j下面是消息队列使用的测试代码:) p: h& q7 o/ f, h% g

( o2 ?7 M" |+ E3 S
  • #include <iostream>
  • #include <cstring>
  • #include <errno.h>
  • #include <unistd.h>
  • #include <fcntl.h>
  • #include <mqueue.h>
  • using namespace std;
  • int main()
  • {
  •     mqd_t mqID;
  •     mqID = mq_open("/anonymQueue", O_RDWR | O_CREAT | O_EXCL, 0666, NULL);
  •     if (mqID < 0)
  •     {
  •         if (errno == EEXIST)
  •         {
  •             mq_unlink("/anonymQueue");
  •             mqID = mq_open("/anonymQueue", O_RDWR | O_CREAT, 0666, NULL);
  •         }
  •         else
  •         {
  •             cout<<"open message queue error..."<<strerror(errno)<<endl;
  •             return -1;
  •         }
  •     }
  •     if (fork() == 0)
  •     {
  •         mq_attr mqAttr;
  •         mq_getattr(mqID, &mqAttr);
  •         char *buf = new char[mqAttr.mq_msgsize];
  •         for (int i = 1; i <= 5; ++i)
  •         {
  •             if (mq_receive(mqID, buf, mqAttr.mq_msgsize, NULL) < 0)
  •             {
  •                 cout<<"receive message  failed. ";
  •                 cout<<"error info:"<<strerror(errno)<<endl;
  •                 continue;
  •             }
  •             cout<<"receive message "<<i<<": "<<buf<<endl;
  •         }
  •         exit(0);
  •     }
  •     char msg[] = "yuki";
  •     for (int i = 1; i <= 5; ++i)
  •     {
  •         if (mq_send(mqID, msg, sizeof(msg), i) < 0)
  •         {
  •             cout<<"send message "<<i<<" failed. ";
  •             cout<<"error info:"<<strerror(errno)<<endl;
  •         }
  •         cout<<"send message "<<i<<" success. "<<endl;
  •         sleep(1);
  •     }
  • }
    / z! {  m/ T3 [: O; q! r
         
& J. X3 M, I6 l( r" K
2 o/ @, |7 `* G9 n( o在Linux 2.6.18下的执行结构如下:5 O+ k+ n, j2 |( T

7 ]/ J; G" T' q: g5 u. I% ?5 L
  • send message 1 success.
  • receive message 1: yuki
  • send message 2 success.
  • receive message 2: yuki
  • send message 3 success.
  • receive message 3: yuki
  • send message 4 success.
  • receive message 4: yuki
  • send message 5 success.
  • receive message 5: yuki
    # f" d  L6 ^7 W

) m$ L7 N* {* C; \' ?2 v% \" N. n
4 POSIX消息队列的限制( u, q+ Z, w7 I$ P3 B( s
) {2 G7 Y: ?8 E0 ~
POSIX消息队列本身的限制就是mq_attr中的mq_maxmsg和mq_msgsize,分别用于限定消息队列中的最大消息数和每个消息的最大字节数。在前面已经说过了,这两个参数可以在调用mq_open创建一个消息队列的时候设定。当这个设定是受到系统内核限制的。( Q* W) D( g1 u; G

( p# E& D$ n' q6 k& K5 p; s* G$ @下面是在Linux 2.6.18下shell对启动进程的POSIX消息队列大小的限制:5 K& J8 v5 x6 E3 V
' l# ~" }7 |& ?1 y
  • # ulimit -a |grep message
  • POSIX message queues     (bytes, -q) 8192002 E# @. U2 d! R  J; ?; X3 O

" l4 R! Y0 x' |
3 ]2 I2 W: W! p& O. c4 q限制大小为800KB,该大小是整个消息队列的大小,不仅仅是最大消息数*消息的最大大小;还包括消息队列的额外开销。前面我们知道Linux 2.6.18下POSIX消息队列默认的最大消息数和消息的最大大小分别为:1 n; J% @2 g. E' R9 I, e, b3 d- c
* x8 d8 ~# U7 T+ W# f, h2 L, B- J, [8 T
  • mq_maxmsg = 10
  • mq_msgsize = 8192
    " g/ b4 y( K7 I& k1 f

/ d5 i8 z% m5 W) d4 z5 ?
, B0 j* ~# c9 p% V5 \# r% e为了说明上面的限制大小包括消息队列的额外开销,下面是测试代码:
! B, h$ g( y0 A* g
) Z7 V' R$ {+ g9 A- r
  • #include <iostream>
  • #include <cstring>
  • #include <errno.h>
  • #include <unistd.h>
  • #include <fcntl.h>
  • #include <mqueue.h>
  • using namespace std;
  • int main(int argc, char **argv)
  • {
  •     mqd_t mqID;
  •     mq_attr attr;
  •     attr.mq_maxmsg = atoi(argv[1]);
  •     attr.mq_msgsize = atoi(argv[2]);
  •     mqID = mq_open("/anonymQueue", O_RDWR | O_CREAT | O_EXCL, 0666, &attr);
  •     if (mqID < 0)
  •     {
  •         if (errno == EEXIST)
  •         {
  •             mq_unlink("/anonymQueue");
  •             mqID = mq_open("/anonymQueue", O_RDWR | O_CREAT, 0666, &attr);
  •             if(mqID < 0)
  •             {
  •                 cout<<"open message queue error..."<<strerror(errno)<<endl;
  •                 return -1;
  •             }
  •         }
  •         else
  •         {
  •             cout<<"open message queue error..."<<strerror(errno)<<endl;
  •             return -1;
  •         }
  •     }
  •     mq_attr mqAttr;
  •     if (mq_getattr(mqID, &mqAttr) < 0)
  •     {
  •         cout<<"get the message queue attribute error"<<endl;
  •         return -1;
  •     }
  •     cout<<"mq_flags:"<<mqAttr.mq_flags<<endl;
  •     cout<<"mq_maxmsg:"<<mqAttr.mq_maxmsg<<endl;
  •     cout<<"mq_msgsize:"<<mqAttr.mq_msgsize<<endl;
  •     cout<<"mq_curmsgs:"<<mqAttr.mq_curmsgs<<endl;
  • }3 e" O# s: z1 m. V3 P. |: d

, R+ R; V& n% d7 t7 [! U# R+ \
# P! s' Z- ^) A3 @) h0 u! |) t        下面进行创建消息队列时设置最大消息数和消息的最大大小进行测试:3 e  Q$ I9 b* c) |

! m* }0 D& D9 M: I( p' w
  • [root@idcserver program]# g++ -g test.cpp -lrt
  • [root@idcserver program]# ./a.out 10 81920
  • open message queue error...Cannot allocate memory
  • [root@idcserver program]# ./a.out 10 80000
  • open message queue error...Cannot allocate memory
  • [root@idcserver program]# ./a.out 10 70000
  • open message queue error...Cannot allocate memory
  • [root@idcserver program]# ./a.out 10 60000
  • mq_flags:0
  • mq_maxmsg:10
  • mq_msgsize:60000
  • mq_curmsgs:0
    ) ?0 z& f. F) A$ A0 u3 c6 x8 Q

5 N. O9 r& M; {6 j# x6 w
4 ~" J& f  g* L  u$ k1 ]从上面可以看出消息队列真正存放消息数据的大小是没有819200B的。可以通过修改该限制参数,来改变消息队列的所能容纳消息的数量。可以通过下面方式来修改限制,但这会在shell启动进程结束后失效,可以将设置写入开机启动的脚本中执行,例如.bashrc,rc.local。8 G. u  w) n, K! h3 _* P7 f0 B

& t" V+ t1 Z- k
  • [root@idcserver ~]# ulimit -q 1024000000
  • [root@idcserver ~]# ulimit -a |grep message
  • POSIX message queues     (bytes, -q) 1024000000
    . A" @! x* K* Y* v* A8 s( m
3 ?. Y/ y$ e! R% q
3 R# Y( j) L+ m
下面再次测试可以设置的消息队列的属性。& ]# P0 Q) b0 p6 \

, v& I  K( `( v1 a- ^6 k6 y/ J# P0 ]
  • [root@idcserver program]# ./a.out 10 81920
  • mq_flags:0
  • mq_maxmsg:10
  • mq_msgsize:81920
  • mq_curmsgs:0
  • [root@idcserver program]# ./a.out 10 819200
  • mq_flags:0
  • mq_maxmsg:10
  • mq_msgsize:819200
  • mq_curmsgs:0
  • [root@idcserver program]# ./a.out 1000 8192
  • mq_flags:0
  • mq_maxmsg:1000
  • mq_msgsize:8192
  • mq_curmsgs:00 `, L3 z* K# _2 Y; x4 {$ |
) i% J; _5 V  v0 B/ b0 v* _

& E# {  t: g* nPOSIX消息队列在实现上还有另外两个限制:* k$ }! r1 J9 e) P( |, Z, n

  G0 t" h- _7 m" ?' u, D: a: |3 UMQ_OPEN_MAX:一个进程能同时打开的消息队列的最大数目,POSIX要求至少为8;# M6 t* C5 `1 c1 F

8 m2 e4 V; ?( x/ o8 d) ]MQ_PRIO_MAX:消息的最大优先级,POSIX要求至少为32;
6 W& a5 A! \. a9 x6 \2 G+ [( L" w; S2 q' h: R$ U
6 x( @5 h1 {" ~. F

该用户从未签到

2#
发表于 2021-4-26 13:10 | 只看该作者
Linux进程通信之POSIX消息队列
您需要登录后才可以回帖 登录 | 注册

本版积分规则

关闭

推荐内容上一条 /1 下一条

EDA365公众号

关于我们|手机版|EDA365电子论坛网 ( 粤ICP备18020198号-1 )

GMT+8, 2025-11-24 12:46 , Processed in 0.171875 second(s), 27 queries , Gzip On.

深圳市墨知创新科技有限公司

地址:深圳市南山区科技生态园2栋A座805 电话:19926409050

快速回复 返回顶部 返回列表