send.c
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <unistd.h>
#include <string.h>
#define MQ_FILE "/hello" //以/开关,并且不能再有/,send和rec的名字要一致
int main()
{
char buf[100];
char input[100];
struct mq_attr attr;
mqd_t mqID;
mqID = mq_open(MQ_FILE, O_RDWR|O_CREAT, 0666, NULL);
if(mqID < 0)
{
if(mqID == -1)
{
mq_unlink(MQ_FILE);
mqID = mq_open(MQ_FILE, O_RDWR|O_CREAT, 0666, NULL);
}
else
{
printf("open error\n");
}
}
while(1)
{
scanf("%s", input);
if(!strcmp(input, "send"))
{
for(int i=0; i<10; i++)
{
static int abc;
sprintf(buf, "%d", abc++);
mq_send(mqID, buf, strlen(buf), 10);
}
}
else if(!strcmp(input, "quit"))
{
mq_unlink(MQ_FILE);
}
}
return 0;
}
rec.c
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <unistd.h>
#include <string.h>
#define MQ_FILE "/hello"
int main()
{
char buf[100];
char input[100];
struct mq_attr attr;
mqd_t mqID;
int get_num = 0;
int prio;
mqID = mq_open(MQ_FILE, O_RDWR);
if(mqID < 0)
{
if(mqID == -1)
{
mq_unlink(MQ_FILE);
mqID = mq_open(MQ_FILE, O_RDWR);
}
else
{
printf("open error\n");
}
}
while(1)
{
mq_getattr(mqID, &attr);
get_num = mq_receive(mqID, buf, attr.mq_msgsize, &prio);//很重要
if(get_num < 0)
{
printf("get error\n");
sleep(1);
}
printf("get %s num is %d, prio is %d \n", buf, get_num, prio);
}
return 0;
}