Program to demonstrate Message Passing IPC

Share

As we already discussed IPC and different techniques for IPC, this article is about the C program for demonstrating the message passing technique for IPC. Again, we are using <sys/shm.h> GCC library. The function looks like this:

msgget((key_t)14534, 0666 | IPC_CREAT);

msgget function arguments: key and flag. it returns int value -1 or 1. -1 means the message queue is not created. And message passing is done through the function msgsnd . it takes arguments: message queue id, message, payload max size, and message flag. msgsnd function looks like:

msgsnd(msgid, (void *)&process_msg, MAX_TEXT, 0)

To demonstrate this process, we create two processes and run them in parallel.

Process 1 ( Sender )

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_TEXT 512 // maximum length of the message that can be sent allowed
struct ipc_msg{
    long int msg_type;
    char some_text[MAX_TEXT];
};
int main(){
    
    int running = 1;
    int msgid;
    struct ipc_msg process_msg;
    char buffer[50]; // array to store user input
    msgid = msgget((key_t)14534, 0666 | IPC_CREAT);
    // -1 means the message queue is not created
    if (msgid == -1){
        printf("Error in creating queue\n");
        exit(0);
    }

    while (running){

        printf("Enter some text:");
        fgets(buffer, 50, stdin);
        process_msg.msg_type = 1;
        strcpy(process_msg.some_text, buffer);
        // msgsnd returns -1 if the message is not sent
        if (msgsnd(msgid, (void *)&process_msg, MAX_TEXT, 0) == -1){
            printf("Msg not sent\n");
        }
        if (strncmp(buffer, "end", 3) == 0){
            running = 0;
        }
    }
}

Process 2 ( Reciever )

 #include<stdlib.h>
 #include<stdio.h>
 #include<string.h>
 #include<unistd.h>
 #include<sys/types.h>
 #include<sys/ipc.h>
 #include<sys/msg.h>
 struct ipc_msg{
         long int msg_type;
         char some_text[BUFSIZ];
 };
 int main()
 {
         int running=1;
         int msgid;
         struct ipc_msg process_msg;
         long int msg_to_rec=0;
         msgid=msgget((key_t)14534,0666|IPC_CREAT);
         while(running)
         {
                 msgrcv(msgid,(void *)&process_msg,BUFSIZ,msg_to_rec,0);                 
                 printf("Data received: %s\n",process_msg.some_text);
                 if(strncmp(process_msg.some_text,"end",3)==0)
                 {
                         running=0;
                 }
         }
          msgctl(msgid,IPC_RMID,0);
 }

Output after running both processes at the same time:

IPC

Source code repository: https://github.com/CodewithSudeep/operating-system-c-program

Other C Programs: https://codewithsudeep.com/category/c-program/

Share
Sudeep Mishra

Sudeep Mishra

Healing

%d bloggers like this: