How to do it…

  1. Invoke the ftok function to generate an IPC key. The filename and ID are supplied while creating the IPC key. These must be the same as what were applied while generating the key for writing the message in the message queue.
  2. Invoke the msgget function to access the message queue that is associated with the IPC key. The message queue that's associated with this key already contains a message that we wrote through the previous program.
  3. Define a structure with two members, mtype and mesg
  4. Invoke the msgrcv function to read the message from the associated message queue. The structure that was defined in Step 3 is passed to this function.
  5. The read message is then displayed on the screen.

The messageqrecv.c program for reading a message from the message queue is as follows:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MSGSIZE 255

struct msgstruc {
long mtype;
char mesg[MSGSIZE];
};

int main()
{
int msqid;
key_t key;
struct msgstruc rcvbuffer;

if ((key = ftok("messagefile", 'a')) == -1) {
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0666)) < 0)
{
perror("msgget");
exit(1);
}
if (msgrcv(msqid, &rcvbuffer, MSGSIZE, 1, 0) < 0)
{
perror("msgrcv");
exit(1);
}
printf("The message received is %s\n", rcvbuffer.mesg);
return 0;
}

Let's go behind the scenes.