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

Linux进程通信之POSIX消息队列

[复制链接]

该用户从未签到

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

EDA365欢迎您登录!

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

x

) p+ Y- ]4 y: j$ A; J% n消息队列是Linux IPC中很常用的一种通信方式,它通常用来在不同进程间发送特定格式的消息数据。  D% {; D% A1 }8 X0 b& Y: z

% n# Y: {4 \! P消息队列和之前讨论过的管道和FIFO有很大的区别,主要有以下两点:
0 P8 A0 M( Z8 f; X
9 L+ a' K" U& n( b$ l! n6 A4 r! t
  • 一个进程向消息队列写入消息之前,并不需要某个进程在该队列上等待该消息的到达,而管道和FIFO是相反的,进程向其中写消息时,管道和FIFO必需已经打开来读,那么内核会产生SIGPIPE信号(感谢shanshan_fangfang的指正)。
  • IPC的持续性不同。管道和FIFO是随进程的持续性,当管道和FIFO最后一次关闭发生时,仍在管道和FIFO中的数据会被丢弃。消息队列是随内核的持续性,即一个进程向消息队列写入消息后,然后终止,另外一个进程可以在以后某个时刻打开该队列读取消息。只要内核没有重新自举,消息队列没有被删除。
    " W& \( e% B  R) M! a% m2 ?

+ f) t8 ?7 W$ U. ]1 B
' P* o* z0 s# u; G4 J* X" o消息队列中的每条消息通常具有以下属性:* u7 d6 Q& p! a* ]

5 T0 f, o" z1 f+ b, S
  • 一个表示优先级的整数;
  • 消息的数据部分的长度;
  • 消息数据本身;# ?; V$ C- ^! L, y' G  S
$ ]- @  z2 r# [, e: t: |
POSIX消息队列的一个可能的设计是一个如下图所示的消息链表,链表头部有消息队列的属性信息。
) F* P- z) ]! e( g
  j! j8 H* l, q2 ~% }
# }: U$ m, U7 D6 q
0 V1 e) g4 ~9 Y; W4 K图1消息队列的可能布局
, O* w' |6 H: O) E, H+ t- c1 ^' j" z5 g( S% J' V+ N
1 POSIX消息队列的创建和关闭
$ i: L- E3 [) r2 bPOSIX消息队列的创建,关闭和删除用到以下三个函数接口:) r" I7 o& l/ @9 A9 A8 x7 m* u
8 L& d1 h# w  z$ d
  • #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,失败返回-1
    7 Z7 E4 b$ ~0 A  d& B) G

0 `: n5 P/ G% j
) q# S: A/ x0 Vmq_open用于打开或创建一个消息队列。
# b6 l1 ^$ ^" K# r4 rname:表示消息队列的名字,它符合POSIX IPC的名字规则。. [: P( `2 w2 A1 I
0 ~% `" G4 v, _0 Y3 F5 t
oflag:表示打开的方式,和open函数的类似。有必须的选项:O_RDONLY,O_WRONLY,O_RDWR,还有可选的选项:O_NONBLOCK,O_CREAT,O_EXCL。
( Y2 K/ L/ _- ]% Q" c+ c5 F2 A4 l, D% O5 v8 T& I3 Q
mode:是一个可选参数,在oflag中含有O_CREAT标志且消息队列不存在时,才需要提供该参数。表示默认访问权限。可以参考open。
  P0 h% {% K0 d% u6 F- _' X" G
) p% T8 Q" g7 K% e% D/ ]attr:也是一个可选参数,在oflag中含有O_CREAT标志且消息队列不存在时才需要。该参数用于给新队列设定某些属性,如果是空指针,那么就采用默认属性。
$ T- g' Y$ k; W& ~& ?5 M. j2 _: a% g4 @% y, P: s
mq_open返回值是mqd_t类型的值,被称为消息队列描述符。在Linux 2.6.18中该类型的定义为整型:& L( L/ O: v2 s5 h

* C  R4 r  i, t# Y  g
  • #include <bits/mqueue.h>
  • typedef int mqd_t;! ^; n. Y7 r4 v9 C$ ^
9 y2 A1 a$ H+ r7 [# t
" s; p. x! T7 B8 g9 C) n
mq_close用于关闭一个消息队列,和文件的close类型,关闭后,消息队列并不从系统中删除。一个进程结束,会自动调用关闭打开着的消息队列。5 P$ w' f4 L! s* H0 P3 I; Z
" `$ x* w. a9 y: r+ s  c( v# b
mq_unlink用于删除一个消息队列。消息队列创建后只有通过调用该函数或者是内核自举才能进行删除。每个消息队列都有一个保存当前打开着描述符数的引用计数器,和文件一样,因此本函数能够实现类似于unlink函数删除一个文件的机制。
+ B5 F% o, U* _
# x% [+ V) v4 O" e8 W. CPOSIX消息队列的名字所创建的真正路径名和具体的系统实现有关,关于具体POSIX IPC的名字规则可以参考《UNIX 网络编程 卷2:进程间通信》的P14。. ?. N9 B1 d/ v" a: ~* `0 `" h5 Y

( A: |* f3 b5 B: g8 K9 s0 V经过测试,在Linux 2.6.18中,所创建的POSIX消息队列不会在文件系统中创建真正的路径名。且POSIX的名字只能以一个’/’开头,名字中不能包含其他的’/’。
% F* {. w% J$ h( X! j* ?  b0 W, t) @" f/ E0 |2 _& g  T0 n

% s6 H. G# A% h5 c2 POSIX消息队列的属性4 S* ?5 V( j$ K6 i. [0 E
" W! P0 h& M' R+ G7 ~" g. P0 n3 g2 Y
POSIX标准规定消息队列属性mq_attr必须要含有以下四个内容:1 q& r' d2 N3 V1 f6 l! ]

. ?! N- Y: d6 C
  • long    mq_flags //消息队列的标志:0或O_NONBLOCK,用来表示是否阻塞
  • long    mq_maxmsg  //消息队列的最大消息数
  • long    mq_msgsize  //消息队列中每个消息的最大字节数
  • long    mq_curmsgs  //消息队列中当前的消息数目# f3 J) u& U1 z$ K2 H* G' G

8 m1 A5 M! w+ A) f# }" ^
" A6 d* d6 i7 d9 s7 Z2 \9 k, y2 a+ q( S在Linux 2.6.18中mq_attr结构的定义如下:
8 x! \6 J' H7 p' b' V" T6 g# W: u* [( q1 `
  • #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];
  • };
    * ^" }- t( b% V& s- w

& Z; {8 }, v, f
! t0 R( o/ K" l7 e0 EPOSIX消息队列的属性设置和获取可以通过下面两个函数实现:
$ j  a% Q: o. ~. K# M) X; i' v8 g  k
  • #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
    $ h& k  X( D$ @

7 z% @7 P: M( @4 Y
5 |- F/ ~- d! Imq_getattr用于获取当前消息队列的属性,mq_setattr用于设置当前消息队列的属性。其中mq_setattr中的oldattr用于保存修改前的消息队列的属性,可以为空。, j: H0 R" i- S( W, s- `

; s  M0 k" h: O$ Z6 z6 X0 Z; Gmq_setattr可以设置的属性只有mq_flags,用来设置或清除消息队列的非阻塞标志。newattr结构的其他属性被忽略。mq_maxmsg和mq_msgsize属性只能在创建消息队列时通过mq_open来设置。mq_open只会设置该两个属性,忽略另外两个属性。mq_curmsgs属性只能被获取而不能被设置。
  |7 |2 d+ V. k7 f- f- n- l: n" D. z3 X& B" T
下面是测试代码:) w1 Z. s/ N8 @- N7 D' W

, ^. @1 Z% R3 J: ^
  • #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/ T+ P1 U' b# H7 ?

. R* K! n  j; u& f# H* [
. R+ V/ |/ V% Z4 t1 M      在Linux 2.6.18中执行结果是:! _5 S  z2 h. K5 ^2 I7 ~
+ Z# e& q- M+ t: M- X1 N. `( V
  • mq_flags:0
  • mq_maxmsg:10
  • mq_msgsize:8192
  • mq_curmsgs:08 a# c: J0 \/ m4 O
: H4 I* l5 x2 i
3 E$ |$ W' L' r+ y' R) a
3 POSIX消息队列的使用" W' x0 J% n/ O7 {& A

5 G7 c- K/ T+ ^; f( n+ oPOSIX消息队列可以通过以下两个函数来进行发送和接收消息:" g- |) E* o; S. b# T2 V5 [

# S( C% Q. x9 Z3 F6 {# p
  • #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
    9 y$ _& p! r/ m5 @

+ f- z2 G5 I+ O/ C: d1 E$ v4 t8 j+ f4 K& ]
" D( c( l" P& p
   mq_send向消息队列中写入一条消息,mq_receive从消息队列中读取一条消息。# u. c" F% z' [$ d! q
; [+ u- W0 n5 M+ k6 ~$ O9 ]. z
mqdes:消息队列描述符;3 e! l  U0 b/ g9 s7 Y* _8 W* e

% R1 E) i) `/ n- imsg_ptr:指向消息体缓冲区的指针;
2 ^6 z' {! r* k! g3 n( O- }; I  ]! Q" i1 w: @7 d: A0 {
msg_len:消息体的长度,其中mq_receive的该参数不能小于能写入队列中消息的最大大小,即一定要大于等于该队列的mq_attr结构中mq_msgsize的大小。如果mq_receive中的msg_len小于该值,就会返回EMSGSIZE错误。POXIS消息队列发送的消息长度可以为0。
3 }8 ^7 _. A. ?. Z( M# N. k+ \8 D' [6 J
msg_prio:消息的优先级;它是一个小于MQ_PRIO_MAX的数,数值越大,优先级越高。POSIX消息队列在调用mq_receive时总是返回队列中最高优先级的最早消息。如果消息不需要设定优先级,那么可以在mq_send是置msg_prio为0,mq_receive的msg_prio置为NULL。
* p2 E! _- X+ e8 K7 E
! k; b# O* X& c还有两个XSI定义的扩展接口限时发送和接收消息的函数:mq_timedsend和mq_timedreceive函数。默认情况下mq_send和mq_receive是阻塞进行调用,可以通过mq_setattr来设置为O_NONBLOCK。
; _/ C2 _) g: S0 |3 Z" [# U2 y
# {' K2 v0 e1 c- w* X# @! _8 H1 x! [
下面是消息队列使用的测试代码:; c0 k1 j* r. L7 t
+ W- s! M4 ~8 K4 s5 H) ^. @7 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);
  •     }
  • }+ D& O6 w& r2 V) |
         
# J* x% C* p0 }) z: B: a6 @* a2 K$ q1 q2 d( ^, E  N' C1 E/ f
在Linux 2.6.18下的执行结构如下:/ v) x# ?, K, r1 Y7 R6 P

3 |$ S# |- G% A% t0 W' c* p, B4 @' x
  • 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
    + l) }/ U+ p2 T% ~( R
/ O: v" N$ k3 c+ S7 `: S
8 K; W7 p9 q7 f
4 POSIX消息队列的限制
% E( ]9 t0 t* L$ _$ b, E
9 i  W; H; [! u0 P' M) r+ nPOSIX消息队列本身的限制就是mq_attr中的mq_maxmsg和mq_msgsize,分别用于限定消息队列中的最大消息数和每个消息的最大字节数。在前面已经说过了,这两个参数可以在调用mq_open创建一个消息队列的时候设定。当这个设定是受到系统内核限制的。
5 V) C2 z. j+ _& _. v
! o4 Q9 W8 }" s0 |: z( a$ m下面是在Linux 2.6.18下shell对启动进程的POSIX消息队列大小的限制:1 T$ _# g* ], v0 f% i$ d

, h5 g" E+ j' f$ W* ?
  • # ulimit -a |grep message
  • POSIX message queues     (bytes, -q) 819200
    * Z- x5 n1 ]0 C: O( Y
- Q! F9 }3 }( u! F. d
: j. s; ]  ^6 \$ \$ G% o9 {
限制大小为800KB,该大小是整个消息队列的大小,不仅仅是最大消息数*消息的最大大小;还包括消息队列的额外开销。前面我们知道Linux 2.6.18下POSIX消息队列默认的最大消息数和消息的最大大小分别为:8 d; u* ?5 y* S" h& \9 T

. z. Z9 L: ~# K* q. W+ g% s
  • mq_maxmsg = 10
  • mq_msgsize = 81923 n7 ^) e* Y1 V4 L0 o
+ U* X' ?+ G& g# g5 W" |0 ]

% f2 d. y3 B9 A# f为了说明上面的限制大小包括消息队列的额外开销,下面是测试代码:4 F. W8 V1 w" i8 U
6 ?5 S: I8 Y2 B$ U, ^
  • #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;
  • }! Q: q( o- c8 C9 R2 \7 R8 w) P2 b

- N+ m6 \4 Z% q
! e" a2 o3 T2 \: h. m        下面进行创建消息队列时设置最大消息数和消息的最大大小进行测试:# h) Y& i! v9 y% u2 k: }
; U& b6 W9 C8 }5 |. ^
  • [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
    : U5 }- b: ^/ @& d$ Z6 n
2 v! W: c8 B. E, H' \

( J* `: B! B; D, i7 ^$ b. A从上面可以看出消息队列真正存放消息数据的大小是没有819200B的。可以通过修改该限制参数,来改变消息队列的所能容纳消息的数量。可以通过下面方式来修改限制,但这会在shell启动进程结束后失效,可以将设置写入开机启动的脚本中执行,例如.bashrc,rc.local。  z! d! x% [/ q2 R( F. q
$ [0 q) K4 c. k" i8 s
  • [root@idcserver ~]# ulimit -q 1024000000
  • [root@idcserver ~]# ulimit -a |grep message
  • POSIX message queues     (bytes, -q) 1024000000
    9 o3 \! ^7 e4 W$ l' _' c2 N

% m+ M3 a2 Z! q: |- Y: c. C5 P# `, m5 R% I- Y$ V4 z
下面再次测试可以设置的消息队列的属性。
8 Q9 B1 d  U  v# Z1 C. z8 Z! T1 S" \6 h9 F
  • [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:0
    * `& r6 V( C* Q; O

7 T, Z* i3 {+ I8 S5 ~2 v/ z7 K' o: c6 H2 u
POSIX消息队列在实现上还有另外两个限制:
. f6 G; I4 N: R) O2 m. c* r; }' ~2 D$ L' y
MQ_OPEN_MAX:一个进程能同时打开的消息队列的最大数目,POSIX要求至少为8;
: V( j6 h+ ^0 p& U3 v8 e" Z! ~+ m
' c' G' b/ d2 a+ V9 XMQ_PRIO_MAX:消息的最大优先级,POSIX要求至少为32;' `. B' ?8 Q4 z  a) H6 o( t0 B& t
7 ]" E& ?4 B9 c" y% J

' i# o8 M: _# ?( @9 T+ L

该用户从未签到

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

本版积分规则

关闭

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

EDA365公众号

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

GMT+8, 2025-11-24 07:32 , Processed in 0.187500 second(s), 27 queries , Gzip On.

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

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

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