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 */
 	size_t           msgsz;     /* message size */
	size_t           maxmsgsize;
 	long             msgtyp;    /* desired message type */
 	int              msqid      /* message queue ID to be used */
 	msgp = malloc(sizeof(struct msgbuf) - sizeof (msgp->mtext) 
							+ maxmsgsz);
 	if (msgp == NULL) {
 		(void) fprintf(stderr, "msgop: %s %ld byte messages.\n",
 				"could not allocate message buffer for", maxmsgsz);
 		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");