Linux进程间通信IPC学习笔记之消息队列(Posix)

基础知识:

消息队列可认为是一个消息链表,有足够写权限的线程可往队列中放置消息,有足够读权限的线程可以从队列中取走消息。在某个进程往一人队列写入消息之前,并不需要另外某个进程在该队列上等待消息的到达。其特性为:

1)具有内核的持续性:即当一个进程往某一个队列写入一些消息后终止,而另一个进程可以在以后的某个时刻取出该消息;

2)

#include <mqueue.h>
mqd_t mq_open(const char *name, int oflag, ...
                         /* mode_t mode,struct mq_attr *attr */);
返回:若成功则返回消息队列描述符,否则返回-1
#include <mqueue.h>
int mq_close(mqd_t mqdes);
返回:若成功返回0,否则返回-1
#include <mqueue.h>
int mq_unlink(const char *name); 
返回:若成功返回0,否则返回-1
#include <mqueue.h>
int mq_send(mqd_t mqdes, const char *msg_ptr, size_t msg_len,
       unsigned msg_prio);
返回:若成功返回0,否则返回-1
ssize_t mq_receive(mqd_t mqdes,
char *msg_ptr, size_t msg_len, unsigned *msg_prio); 返回:若成功返回消息中字节数,否则返回-1 #include <mqueue.h> int mq_getattr(mqd_t mqdes, struct mq_attr *mqstat); int mq_setattr(mqd_t mqdes, const struct mq_attr *restrict mqstat, struct mq_attr *restrict omqstat); 返回:若成功返回0,否则返回-1 #include <mqueue.h> #include <time.h> ssize_t mq_timedreceive(mqd_t mqdes, char *restrict msg_ptr, size_t msg_len, unsigned *restrict msg_prio, const struct timespec *restrict abs_timeout); int mq_timedsend(mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned msg_prio, const struct timespec *abs_timeout); #include <mqueue.h> int mq_notify(mqd_t mqdes, const struct sigevent *notification);
返回:若成功返回0,否则返回-1

 

struct mq_attr{
   long mq_flags;         //message queue flags
   long mq_maxmsg;   //maximum number of messages
   long mq_msgsize;   //maximum message size
   long mq_curmsgs;  //number of messages currently queued
};

struct sigevent
{
int                 sigev_notify;                             //notification type
int                 sigev_signo;                              //signal number
union sigval    sigev_value;                             //signal value
void (*sigev_notify_function)  (union sigval);   //notification function
pthread_attr_t *sigev_notify_attributes;          //notification attributes
}

union sigval
{
int sival_int; //integer value
void *sival_ptr; //pointer value
}
View Code

 

 

测试代码:

 

参考资料:

posted on 2013-08-29 20:21  鹰之翔  阅读(325)  评论(0编辑  收藏  举报

导航