CST8217 - Lab Exercise 3

Message queues

Write two simple programs to demonstrate the use of message queues, one to create a queue and send lines from a file to it until EOF is reached. The other program will locate the message queue, receive lines from it, and write them to another file. Either or both programs can run in the background. You should have the second program (read queue and writes to file) remove the now-empty message queue.

Program 1 will use msgget() and perhaps ftok() to create a message queue. Remember that your second program will have to use the same key in order to find the message queue. Now read your input file and use msgsnd() to put each line into the queue. When you reach the end of the input file, put a distinctive message on the queue so your other program will recognize that program 1 is finished (like the CST8204 FIFO exercise).

Program 2 will also use msgget() (and perhaps ftok()), this time to obtain the msgid of the message queue already created. Use msgrcv()in a loop to get the messages which you will then write into an output file. When it recognizes the end of file message sent by program 1, close the output file and delete the message queue with msgctl().

Your message structure should look much like this, where SIZE is large enough for your longest line:

struct {

long mtype;

char mtext[SIZE];

} msgbuf;

All message queue functions require the same set of include files, and all will return -1 and set errno if an error occurs:

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/msg.h>

See the lab prep document for a summary of the message queue functions.

Since you have two separate programs that can share some source code, you should create a Makefile to simplify your work. You may recall that you can use a false default target (it's always the first target) to force both programs to be compiled:

both: program1 program2

... where "both" can be nearly any word you like ("all" is also common) followed by the names of both executable programs, whatever they are.

Always check with ipcs(1) and use ipcrm(1) to make sure you have not left any IPC structures on your machine. If you don't, people will laugh and point.