# include <mqueue.h> mqd_t mq_open(const char *name, int oflag); mqd_t mq_open(const char *name, int oflag, mode_t mode, struct mq_attr *attr); |
创建一个新的消息队列或打开一个已存在的消息队列
oflag参数是:
O_RDONLY
Open the queue to receive messages only.
O_WRONLY
Open the queue to send messages only.
O_RDWR
Open the queue to both send and receive messages.
Zero or more of the following flags can additionally be ORed in oflag:
O_NONBLOCK
Open the queue in non-blocking mode. In circumstances where mq_receive(3) and mq_send(3)
would normally block, these functions instead fail with the error EAGAIN.
O_CREAT
Create the message queue if it does not exist. The owner (user ID) of the message queue is set to the effective user ID of the calling process. The group ownership (group ID) is set to the effective group ID of the calling process.
O_EXCL
If O_CREAT was specified in oflag, and a queue with the given name already exists, then fail with the error EEXIST.
int mq_close(mqd_t mqdes) 返回:成功时为0,出错时为-1 |
int mq_unlink(const char * name); 返回:成功时为0,出错时为-1 |
一个消息队列的名字在系统中的存在本身也占用其引用计数器的一个引用数,mq_unlink从系统中删除该名字意味着同时将其引用计数减1,若变为0则真正拆除该队列。
属性:
int mq_getattr(mqd_t mqdes, struct mq_attr * attr); |
int mq_setattr(mqd_t mqdes, const struct mq_attr * attr, struct mq_attr * oattr); 都返回:成功0,失败-1 |
mq_attr的结构如下:
struct mq_attr{
long mq_flags;
long mq_maxmsg; //队列中的最大消息数
long mq_msgsize; //任意给定消息的最大字节数
long mq_curmsgs;
};
发送与接收:
int mq_send(mqd_t mqdes, const char * ptr, size_t len, unsigned int prio); 返回:成功时为0,出错时为-1 ssize_t mq_receive(mqd_t mqdes, char * ptr, size_t len , unsigned int *priop); 返回:成功时为消息中的字节数,出错为-1 |
通知:
当有一个消息放到消息队列时,我们怎样得到他呢?调用mq_receive阻塞的话会阻止我们其间做其他事,如果设置非阻塞标志,我们必须轮训,这样消耗CPU时间。可以使用posix消息队列的异步通知方式。
异步通知,已告知何时有一个消息放到了某个空的消息队列。这种统治有两种方式可供选择:产生一个新号;创建一个线程执行一个指定的函数。
int mq_notify(mqd_t mqdes, const struct sigevent * notification); 返回:成功时为0,出错时为-1 |
union sigval { /* Data passed with notification */
int sival_int; /* Integer value */
void *sival_ptr; /* Pointer value */
};
struct sigevent {
int sigev_notify; /* Notification method */
int sigev_signo; /* Notification signal */
union sigval sigev_value; /* Data passed with
notification */
void (*sigev_notify_function) (union sigval);
/* Function for thread
notification */
void *sigev_notify_attributes;
/* Thread function attributes */
};
通知的编程方法可能产生多种问题(详见unix网络编程第二卷)
#include <signal.h> int sigwait(const sigset_t * set, int * sig); 返回:成功时为0,出错时为正的Exx值 |