Listing 4

func()
{
   int msqid, msglen;
   long msgtype;
   char string[80];
   struct mssg {
       long mtype;
       char mtext[BUFSIZ];
   } msgbuf;

   /* Ask the user if their looking
    * for a particular message type.
   */
   printf("Enter message type or hit <RETURN> for the \
first message on queue: ");

   gets(string);
   if (*string == NULL)
       msgtype=0;
   else
       sscanf(string,"%ld",&msgtype));

   /* Attempt to receive a message. The kernel
    * will put the process to sleep until
    * a message arrives.
   */
   if ((msglen=msgrcv(msqid, &msgbuf, BUFSIZ, msgtype, 0)) == -1) {
       /* The perror(3C) function prints the
        * text of the error number contained
        * in the external integer errno.
       */
           perror("msgget() failed: ");
           return(-1);
   }

   /* NULL terminate the message */
   msgbuf.mtext[msglen]=NULL;

   return(0);
}