[请教]哪位大侠可以帮助给一个mq_notify的使用实例?

不知道该如何正确使用mq_notify?看了它的帮助,是不是说只有当消息队列由空变为非空时才会产生notification?我在经典的unix network programming II(IPC communication)中找到一个使用线程的例子,可是使用时仍然是如果发送程序先于接收程序执行,已经发送数据到消息队列的话,则接收程序就不会去接收。请帮帮忙看看问题在哪里,有没有调试正确的mq_notify例子可供借鉴?非常感谢!

mqd_t mqd;
struct mq_attr attr;
struct sigevent sigev;
#define mq_path “ttest11”
static void notify_thread(union sigval);
int main()
{
mqd=mq_open(mq_path,O_RDONLY|O_NONBLOCK);
mq_getattr(mqd,&attr);
sigev.sigev_notify=SIGEV_THREAD;
sigev.sigev_value.sival_ptr=NULL;
sigev.sigev_notify_function=notify_thread;
sigev.sigev_notify_attributes=NULL;

mq_notify(mqd,&sigev);
for( ; ; )
{
pause();
}

exit(0);
}
static void sig_usr1(union sigval arg)
{
ssize_t n;
void *buff;
buff=malloc(attr.mq_msgsize);
printf(“notify_thread started\n”);
mq_notify(mqd,&sigev);
while((n=mq_receive(mqd,buff,attr.msg_size,NULL))>0)
{
printf(“receive %d bytes and buff is %s\n”,n,buff);
}
if(errno!=EAGAIN)
fprintf(stderr,“mq_receive error!\n”);
}
free(buff);
pthread_exit(NULL);

}

是,只有从空到非空才会有通知,所以在设了mq_notify()以后,还要用mq_receive()先把队列里的消息吸干。

谢谢唐先生的帮助!另外,还有一个问题是消息队列中的数据只能是char类型的其他的数据类型都不行? 比如我只想用消息队列来放一些uint8_t的整数,怎么办呢?我试了发送和接收两边都为uint8_t的数组时失败,其中包含有为0的数据.

失败时候的出错信息是什么呢?数据里有没有0没有关系的。

uint8_t mydata[20];
......
mq_send(mqd, (char *)mydata, 20, 10);

非常感谢唐先生,这样修改后完全正确了.