// Experiment 21(i): Inter-Process Communication using MESSAGE QUEUE
// RECEIVER program
// Compile: gcc 21a_msg_queue_receiver.c -o msgreceiver
// Run    : ./msgreceiver  (waits for a message from msgsender, then removes queue)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct msg_buffer {
    long  msg_type;
    char  msg_text[100];
};

int main() {
    key_t key = ftok("progfile", 65);

    int msgid = msgget(key, 0666 | IPC_CREAT);
    if (msgid < 0) { perror("msgget"); exit(1); }

    struct msg_buffer message;
    if (msgrcv(msgid, &message, sizeof(message.msg_text), 1, 0) < 0) {
        perror("msgrcv"); exit(1);
    }
    printf("Received message: %s\n", message.msg_text);

    // Destroy the message queue
    msgctl(msgid, IPC_RMID, NULL);
    return 0;
}
