os_lab_9pgm
os_lab_9pgm
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
int main() {
key_t key; // Message queue key
int msgid; // Message queue ID
struct msg_buffer message;
if (key == -1) {
perror("ftok failed");
exit(1);
}
if (msgid == -1) {
perror("msgget failed");
exit(1);
}
// Part (b): Send message to the message queue
printf("Enter message number: ");
scanf("%d", &message.msg_number);
getchar(); // To consume the newline character left by scanf
return 0;
}
Explanation:
1. Message Queue Creation:
o ftok() generates a unique key for the message queue using a file
(msgqueue.c in this case) and a project ID (65). This key is used by
msgget() to create a message queue.
o msgget() creates a message queue if it doesn't already exist or
retrieves the ID of an existing queue.
o 0666 | IPC_CREAT gives read and write permissions to the
message queue for all users.
2. Sending Message:
o The msg_buffer struct is used to store the message, which consists
of a message type (msg_type), a message number (msg_number),
and the message text (msg_text).
o msgsnd() sends the message to the queue. The sizeof(message) -
sizeof(long) is used to avoid counting the size of the long field
msg_type.
3. Receiving Message:
o msgrcv() is used to receive a message from the message queue.
The message type specified is 1 (this matches the type of message
sent earlier). The received message is then displayed.
4. Cleaning Up:
o The message queue is deleted using msgctl() with the IPC_RMID
option after the message is received.
Compilation and Execution:
1. Save the code in a file (e.g., msgqueue.c).
2. Compile the program using gcc:
gcc msgqueue.c –
./a.out