Message Queue

POSIX Message Queue

Message queues allow processes to exchange messages in the form of data blocks. They can be more flexible than pipes because messages can be sent and received in any order.

#include <iostream>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <cstring>
 
struct message {
    long mtype;
    char mtext[100];
};
 
int main() {
    key_t key = ftok("progfile", 65);
    int msgid = msgget(key, 0666 | IPC_CREAT);
 
    pid_t pid = fork();
    if (pid == 0) {
        // Child process: Read from message queue
        message msg;
        msgrcv(msgid, &msg, sizeof(msg.mtext), 1, 0);
        std::cout << "Child received: " << msg.mtext << std::endl;
    } else {
        // Parent process: Send to message queue
        message msg;
        msg.mtype = 1;
        strcpy(msg.mtext, "Hello from parent!");
        msgsnd(msgid, &msg, sizeof(msg.mtext), 0);
        wait(NULL);  // Wait for child to finish
    }
 
    msgctl(msgid, IPC_RMID, NULL);  // Remove message queue
    return 0;
}