Programming Interfaces Guide

Sending and Receiving Messages

msgsnd(2) and msgrcv(2) 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. The msgflg argument passes various control flags.

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;    /* maximum message size */
        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");