System Interface Guide

Sending and Receiving Messages

The msgsnd(2) and msgrcv(2) functions send and receive messages, respectively. The msqid argument must be the ID of an existing message queue. The msgp argument is a pointer to a structure that contains the type of the message and its text. The msgsz argument specifies the length of the message in bytes. Various control flags can be passed in the msgflg argument.

The following code illustrates msgsnd(2) and msgrcv(2):


#include <sys/types.h>
 #include <sys/ipc.h>
 #include <sys/msg.h>

 ...
 	int				msgflg;	/* message flags for the operation */
 	struct msgbuf 				*msgp;		/* pointer to the message buffer */
 	int				msgsz;		/* message size */
 	long				msgtyp;		/* desired message type */
 	int				msqid		/* message queue ID to be used */
 	...
 	msgp = (struct msgbuf *)malloc((unsigned)(sizeof(struct msgbuf)
 				- sizeof msgp->mtext + maxmsgsz));
 	if (msgp == NULL) {
 		(void) fprintf(stderr, "msgop: %s %d byte messages.\n",
 				"could not allocate message buffer for", maxmsgsz);
 		exit(1);
 		...
 		msgsz = ...
 		msgflg = ...
 		if (msgsnd(msqid, msgp, msgsz, msgflg) == -1)
 			perror("msgop: msgsnd failed");
 		...
 		msgsz = ...
 		msgtyp = first_on_queue;
 		msgflg = ...
 		if (rtrn = msgrcv(msqid, msgp, msgsz, msgtyp, msgflg) == -1)
 			perror("msgop: msgrcv failed");
 		...