Reputation: 41
My program is receiving wrong data on msgrcv
function if flag is set to 0, however, if i set flag to 1 for specific data then msgrcv
function is keep waiting. I defined send and receive function in common file and calling it from sender and receiver file. I checked debug data and it was sent properly but on receiving end if flag set to 0 means receive first packet then i am getting wrong data. If set flag to 1 which means specific message type data msgrcv
function ended in waiting state. Please help.
/CommonMsgQueue.c/
int InitializeMsgQueue(char *keypath)
{
key_t key;
int msgid;
key = ftok(keypath,'B');
if (key == -1 )
{
perror("Failed to generate key ");
exit(0);
}
msgid = msgget(key, 0666 | IPC_CREAT );
if ( msgid == -1 )
{
perror("Failed to get msgid");
exit(0);
}
return msgid;
}
int SendMsg(key_t msgqid ,StMesgQ *MsgData , int msglength)
{
int iRetVal =0;
iRetVal = msgsnd(msgqid,&MsgData,sizeof(StMesgQ),IPC_NOWAIT);
if ( iRetVal == -1 )
{
perror("Failed to send message");
}
return iRetVal;
}
int RcvMsg(key_t msgqid, StMesgQ *MsgData , int msglength)
{
int iRetVal =0;
iRetVal = msgrcv(msgqid,&MsgData,msglength,0,0);
if (iRetVal == -1 )
{
perror("Failed to receive message ");
exit(0);
}
return iRetVal;
}
/*Sender.c*/
msgqid = InitializeMsgQueue("/home/nprabhat/Nitesh/Nitesh_FrameWork/Key/ClientQueue");
CommonSHMData = (struct CommonSHM*)ShmData;
StMesgQ obj;
while (1)
{
printf("Sender:-- Enter the value For iIndex\n");
scanf("%d",&value);
CommonSHMData->iIndex = value;
CommonSHMData->iIndex2 = value;
DataPktToSend = (char*)CommonSHMData;
memcpy(&obj.buf,&DataPktToSend,strlen(DataPktToSend));
obj.iMsgType = 1;
SendMsg(msgqid,&obj,sizeof(StMesgQ));
}
/*Reciever.c*/
RcvMsg(msgqid,&MsgData,sizeof(StMesgQ));
CommonSHMData_Recv = (struct CommonSHM*)MsgData.buf;
printf("Data Received from queue is %d",CommonSHMData_Recv->iIndex);
Upvotes: 0
Views: 136
Reputation: 16540
regarding:
iRetVal = msgrcv( msgqid, &MsgData, msglength, 0, 0 );
if (iRetVal == -1 )
{
perror("Failed to receive message ");
exit(0);
}
memcpy(&MsgData,&RcvMsgData,sizeof(StMesgQ));
the function: memcpy()
copies from right to left.
Here is the syntax:
void *memcpy(void *destination, const void *source, size_t n);
So the call to memcpy()
is overlaying the data placed in MsgData
by the call to msgrcv()
with whatever trash happens to be in RcvMsgData
Upvotes: 1