Write a C program that receives the messages(From the above message queue as specified in (21)) and display them.

AIM:

Write a C program that receives the messages(From the above message queue as specified in (21) and display them.

Program:

#include <sys/types.h>    
#include <sys/ipc.h> 
#include <sys/msg.h> 
#include <stdio.h> 
#define MSGSZ 128   
/* 
 * Declare the message structure.  */  
typedef struct msgbuf { 
    long    mtype; 
    char    mtext[MSGSZ]; 
} message_buf;  
main() 
{ 
    int msqid; 
    key_t key; 
    message_buf  rbuf;  
    /* 
     * Get the message queue id for the 
     * "name" 1234, which was created by 
     * the server. 
     */ 
    key = 1234; 
    if ((msqid = msgget(key, 0666)) < 0) { 
        perror("msgget"); 
        exit(1); 
    }  
    /* 
     * Receive an answer of message type 1. 
     */ 
    if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) { 
        perror("msgrcv");  
        exit(1);  
   } 
     /* 
     * Print the answer. 
     */ 
    printf("%s\n", rbuf.mtext); 
    exit(0); 
}   

Execution Steps:  
[student@gcet ~]$cc message_send.c 
[student@gcet ~]$ mv a.out msgsend  
[student@gcet ~]$  ./msgsend 
msgget: Calling msgget(0x4d2,01666) 
msgget: msgget succeeded: msqid = 0 
msgget: msgget succeeded: msqid = 0 
msgget: msgget succeeded: msqid = 0 
Message: "Did you get this?" Sent 
[student@gcet ~]$ cc message_rec.c 
[student@gcet ~]$ mv a.out msgrec 
[student@gcet ~]$./msgrec 

Output:

[1] 2907 
[student@gcet ~]$ Did you get this?