How to do it…

  1. Generate an IPC key by invoking the ftok function. A filename and ID are supplied while creating the IPC key.
  2. Invoke the msgget function to create a new message queue. The message queue is associated with the IPC key that was created in step 1.
  3. Define a structure with two members, mtype and mesg. Set the value of the mtype member to 1.
  4. Enter the message that's going to be added to the message queue. The string that's entered is assigned to the mesg member of the structure that we defined in step 3.
  5. Invoke the msgsnd function to send the entered message into the message queue.

The messageqsend.c program for writing the message to the message queue is as follows:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MSGSIZE 255

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

int main()
{
int msqid, msglen;
key_t key;
struct msgstruc msgbuf;
system("touch messagefile");
if ((key = ftok("messagefile", 'a')) == -1) {
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0666 | IPC_CREAT)) == -1) {
perror("msgget");
exit(1);
}
msgbuf.mtype = 1;
printf("Enter a message to add to message queue : ");
scanf("%s",msgbuf.mesg);
msglen = strlen(msgbuf.mesg);
if (msgsnd(msqid, &msgbuf, msglen, IPC_NOWAIT) < 0)
perror("msgsnd");
printf("The message sent is %s\n", msgbuf.mesg);
return 0;
}

Let's go behind the scenes.