message queue(IPC) receiving process not printing the received data in C

I am implementing message queue mechanism for IPC in C linux. Below is my receiving process. It's not printing the message received. It's generating a valid msqid, and other parameters of msgrcv function are also correct, I think. Why so?

//header files
#include"msgbuf.h"
int main()
{
   int msqid;
   key_t key;
   int msgflg = 0666;
   message_buf  *rbuf;
   rbuf=malloc(sizeof(*rbuf));
   rbuf->m=malloc(sizeof(M1));
   key = ftok("/home/user",12);
   if ((msqid = msgget(key, msgflg)) ==-1)
   {
        perror("msgget");
        exit(1);
   }
   printf("\n\n%d\n",msqid);  //working fine till here.
   /* Receive an answer of message type 1.   */
   if (msgrcv(msqid, &rbuf, sizeof(rbuf->m), 1, 0) < 0)
   {
        perror("msgrcv");
        exit(1);
   }
   /* Print the answer.  */
   printf("Received message text= %s\n", rbuf->m->cp);
   return 0;
}

now msgbuf.h

typedef struct msgclient
{
  int msglen;
  int msgtype;
  char *cp;
}M1;


typedef struct msgbuf1
{
   long    mtype;
   M1      *m;
} message_buf;

Answers


if (msgrcv(msqid, &rbuf, sizeof(rbuf->m), 1, 0) < 0)

Should be

if (msgrcv(msqid, &rbuf, sizeof(struct message_buf), 1, 0) < 0)

Since two separate processes have two separate memory areas it doesn't make sense to pass pointers to another process since the passed pointer, if it points to anything at all in the receiving process, won't be pointing to whatever it was pointing to in the originating process.

You will need to change the char *cp; in M1 to a character array and copy the string into it before sending the message buffer. A length byte indicating the length of string might be advisable (but not necessarily required) as well.


Need Your Help