How it works...

First, we will invoke the ftok function to generate an IPC key. The filename and ID that are supplied while creating the IPC key are messagefile and a, respectively. These filenames and ID must be the same as the ones that were applied while generating the key for writing the message in the message queue. The generated key is assigned to the key variable.

Thereafter, we will invoke the msgget function to access the message queue that is associated with the IPC key. The identifier of the accessed message queue is assigned to the msqid variable. The message queue that's associated with this key already contains the message that we wrote in the previous program.

Then, we will define a structure by the name msgstruc with two members, mtype and mesg. The mtype member is for determining the sequence number of the message to be read from the message queue. The mesg member will be used for storing the message that is read from the message queue. We will then define a variable called rcvbuffer of the msgstruc structure type. We will invoke the msgrcv function to read the message from the associated message queue.

The message identifier, msqid, is passed to the function, along with the rcvbuffer the structure whose mesg member will store the read message. After successful execution of the msgrcv function, the mesg member of the rcvbuffer containing the message from the message queue will be displayed on screen.

Let's use GCC to compile the messageqsend.c program, as follows:

$ gcc messageqsend.c -o messageqsend

If you get no errors or warnings, this means that the messageqsend.c program has compiled into an executable file, messageqsend.exe. Let's run this executable file:

$ ./messageqsend
Enter a message to add to message queue : GoodBye
The message sent is GoodBye

Now, press Alt + F2 to open a second Terminal screen. On this screen, you can compile and run the script for reading the message from the message queue.

Let's use GCC to compile the messageqrecv.c program, as follows:

$ gcc messageqrecv.c -o messageqrecv

If you get no errors or warnings, this means that the messageqrecv.c program has compiled into an executable file, messageqrecv.exe. Let's run this executable file:

$ ./messageqrecv
The message received is GoodBye

Voila! We've successfully passed a message from one process to another using the message queue. Let's move on to the next recipe!