i am trying to receive mq_receive() the data from the sender mq_sender() it works when i used to run the send file first .. but if i run receive first it will block even though after send the data to the queue..i attached my code below
//sender
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<mqueue.h>
#include<string.h>
#include<unistd.h>
#define NAME "/queone"
#define MAX_SIZE 1021
void main()
{
int i;
struct mq_attr attr;
attr.mq_maxmsg = 10;
attr.mq_msgsize = MAX_SIZE;
int fd;
char s[MAX_SIZE]="hello";
int r1,r2;
mq_unlink(NAME);
perror("mq_unlink");
fd=mq_open(NAME,O_CREAT | O_WRONLY ,0664,&attr);
printf("fd=%d\n",fd);
for(i=0;i<5;i++)
r1=mq_send(fd,s,sizeof(s),0);
printf("%d",r1);
}
//receiver
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<mqueue.h>
#include<string.h>
#include<unistd.h>
#define NAME "/queone"
#define MAX_SIZE 1021
void main()
{
struct mq_attr attr;
attr.mq_maxmsg = 10;
attr.mq_msgsize = MAX_SIZE;
int fd,fd1,r;
char s[MAX_SIZE];
fd=mq_open(NAME,O_CREAT|O_RDONLY ,0664,&attr);
perror("mq_open");
printf("fd=%d\n",fd);
mq_getattr(fd,&attr);
printf("%d\n",attr.mq_curmsgs);
printf("%d\n",attr.mq_msgsize);
r=mq_receive(fd,s,sizeof(s),0);
printf("%d",r);
if(r==-1)
perror("mq_receive");
printf("%s\n",s);
mq_unlink(NAME);
}
how to handle this
The problem is that you unconditionally call mq_unlink
in the sender. Here's what's happening because of that:
Since the message queue that the sender sent the message to isn't the one that the receiver is listening on, the receiver obviously doesn't receive the message.