Step-by-Step Explanation
1. Define the Message Structure
c
CopyEdit
struct msg_buffer {
long msg_type; // Message type (must be a positive number)
char msg_text[MSG_SIZE]; // Message content
};
The message structure contains:
o msg_type: Used to categorize messages.
o msg_text: The actual message being sent.
2. Create a Message Queue
c
CopyEdit
msgid = msgget(MSG_KEY, 0666 | IPC_CREAT);
if (msgid == -1) {
perror("msgget failed");
exit(EXIT_FAILURE);
}
msgget(MSG_KEY, 0666 | IPC_CREAT)
o Creates a message queue with a unique key (MSG_KEY = 1234).
o 0666: Sets read & write permissions for all users.
o IPC_CREAT: Ensures the queue is created if it doesn’t exist.
Error Handling: If msgget() fails, perror() prints an error message.
3. Get User Input
c
CopyEdit
printf("Enter a message to send to the child process: ");
fgets(message.msg_text, sizeof(message.msg_text), stdin);
message.msg_text[strcspn(message.msg_text, "\n")] = 0; // Remove trailing
newline
message.msg_type = 1; // Message type (must be > 0)
The parent process reads a message from the user.
Removes the trailing newline (\n) to ensure proper formatting.
Sets msg_type = 1, which is required by msgrcv().
4. Create a Child Process
c
CopyEdit
pid = fork();
if (pid == -1) {
perror("fork failed");
exit(EXIT_FAILURE);
}
Creates a child process using fork().
Handles errors if the fork operation fails.
5. Communication Between Parent & Child
Child Process (Reader)
c
CopyEdit
if (pid == 0) {
// Receive the message from the message queue
if (msgrcv(msgid, &message, sizeof(message), message.msg_type, 0) == -1) {
perror("msgrcv failed");
exit(EXIT_FAILURE);
}
printf("Child received message: %s\n", message.msg_text);
// Remove the message queue
msgctl(msgid, IPC_RMID, NULL);
}
msgrcv(msgid, &message, sizeof(message), message.msg_type, 0)
o Reads a message from the queue.
o msg_type = 1 ensures it receives only messages of this type.
o If msgrcv() fails, it prints an error and exits.
Prints the received message.
Deletes the message queue (msgctl(msgid, IPC_RMID, NULL)).
Parent Process (Sender)
c
CopyEdit
else {
// Send the message to the message queue
if (msgsnd(msgid, &message, sizeof(message), 0) == -1) {
perror("msgsnd failed");
exit(EXIT_FAILURE);
}
printf("Parent sent message: %s\n", message.msg_text);
// Wait for the child process to finish
wait(NULL);
}
Sends the message to the queue using:
c
CopyEdit
msgsnd(msgid, &message, sizeof(message), 0);
Waits (wait(NULL)) for the child process to finish.
Example Output
Execution Flow
mathematica
CopyEdit
Enter a message to send to the child process: Hello, Message Queue!
Parent sent message: Hello, Message Queue!
Child received message: Hello, Message Queue!
Memory Cleanup
The child process removes the message queue after receiving the message.