confide

导航

unix编程——posix消息队列

两个简单的消息队列发送和接受的例子:

send.c:

#include <stdlib.h>
#include
<stdio.h>
#include
<mqueue.h>
#include
<sys/stat.h>
int main()
{
mqd_t mqd;
struct mq_attr attr;
int flags;
flags
= O_RDWR | O_CREAT;
mqd
= mq_open("/temp.1234",flags,S_IRUSR|S_IWUSR|S_IROTH|S_IWOTH,NULL);
mq_getattr(mqd,
&attr);
mq_send(mqd,
"abc",3,0);
mq_close(mqd);
exit(
0);
}

recv.c

#include <stdlib.h>
#include
<stdio.h>
#include
<mqueue.h>
#include
<sys/stat.h>
int main()
{
mqd_t mqd;
struct mq_attr attr;
char*buff;
unsigned prio;
ssize_t n;
int flags;
flags
= O_RDWR | O_CREAT;
mqd
= mq_open("/temp.1234",flags,S_IRUSR|S_IWUSR|S_IROTH|S_IWOTH,NULL);
mq_getattr(mqd,
&attr);
buff
= malloc(attr.mq_msgsize);
n
= mq_receive(mqd,buff,attr.mq_msgsize,&prio);
printf(
"%ld b, %s ,pri = %u\n",(long)n,buff,prio);
mq_close(mqd);
exit(
0);
}

linux下编译运行:

gcc -o send send.c -lrt

gcc -o recv recv.c -lrt

./send

./recv

输出:

3 b, abc ,pri = 0

posted on 2011-08-08 23:51  confide  阅读(290)  评论(0)    收藏  举报