0% found this document useful (0 votes)
7 views2 pages

C Message Queue Implementation

This C program demonstrates the use of System V message queues for inter-process communication. It creates a message queue, allows the user to send a message, receives the message, and then cleans up by removing the message queue. Error handling is included for each operation to ensure robustness.

Uploaded by

ggottamsindhu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

C Message Queue Implementation

This C program demonstrates the use of System V message queues for inter-process communication. It creates a message queue, allows the user to send a message, receives the message, and then cleans up by removing the message queue. Error handling is included for each operation to ensure robustness.

Uploaded by

ggottamsindhu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#include <stdio.

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

#define MAX_SIZE 1024

// Define a structure for the message


struct message {
long mtype; // Message type
char mtext[MAX_SIZE]; // Message data
};

int main() {
int msqid;
key_t key;
struct message msg;

// Generate a key for the message queue


key = ftok(".", 'b');
if (key == -1) {
perror("ftok");
exit(1);
}

// Create a message queue


msqid = msgget(key, IPC_CREAT | 0666);
if (msqid == -1) {
perror("msgget");
exit(1);
}

// Write data to the message queue


printf("Enter a message to send: ");
fgets([Link], MAX_SIZE, stdin);
[Link] = 1; // Message type can be any non-zero positive integer

if (msgsnd(msqid, &msg, strlen([Link]) + 1, 0) == -1) {


perror("msgsnd");
exit(1);
}

printf("Message sent.\n");

// Read data from the message queue


if (msgrcv(msqid, &msg, MAX_SIZE, 1, 0) == -1) {
perror("msgrcv");
exit(1);
}

printf("Message received: %s", [Link]);

// Remove the message queue


if (msgctl(msqid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}

return 0;
}

You might also like