The Wayback Machine - https://web.archive.org/web/20240906114745/https://www.geeksforgeeks.org/ipc-using-message-queues/
Open In App

IPC using Message Queues

Last Updated : 25 Nov, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite : Inter Process Communication 
A message queue is a linked list of messages stored within the kernel and identified by a message queue identifier. A new queue is created or an existing queue opened by msgget(). 
New messages are added to the end of a queue by msgsnd(). Every message has a positive long integer type field, a non-negative length, and the actual data bytes (corresponding to the length), all of which are specified to msgsnd() when the message is added to a queue. Messages are fetched from a queue by msgrcv(). We don’t have to fetch the messages in a first-in, first-out order. Instead, we can fetch messages based on their type field.
All processes can exchange information through access to a common system message queue. The sending process places a message (via some (OS) message-passing module) onto a queue which can be read by another process. Each message is given an identification or type so that processes can select the appropriate message. Process must share a common key in order to gain access to the queue in the first place.
 

System calls used for message queues: 
 

  • ftok(): is use to generate a unique key.
  • msgget(): either returns the message queue identifier for a newly created message queue or returns the identifiers for a queue which exists with the same key value.
  • msgsnd(): Data is placed on to a message queue by calling msgsnd().
  • msgrcv(): messages are retrieved from a queue.
  • msgctl(): It performs various operations on a queue. Generally it is use to destroy message queue.

 

MESSAGE QUEUE FOR WRITER PROCESS 
 

C




// C Program for Message Queue (Writer Process)
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX 10
  
// structure for message queue
struct mesg_buffer {
    long mesg_type;
    char mesg_text[100];
} message;
  
int main()
{
    key_t key;
    int msgid;
  
    // ftok to generate unique key
    key = ftok("progfile", 65);
  
    // msgget creates a message queue
    // and returns identifier
    msgid = msgget(key, 0666 | IPC_CREAT);
    message.mesg_type = 1;
  
    printf("Write Data : ");
    fgets(message.mesg_text,MAX,stdin);
  
    // msgsnd to send message
    msgsnd(msgid, &message;, sizeof(message), 0);
  
    // display the message
    printf("Data send is : %s \n", message.mesg_text);
  
    return 0;
}


MESSAGE QUEUE FOR READER PROCESS 
 

C




// C Program for Message Queue (Reader Process)
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
  
// structure for message queue
struct mesg_buffer {
    long mesg_type;
    char mesg_text[100];
} message;
  
int main()
{
    key_t key;
    int msgid;
  
    // ftok to generate unique key
    key = ftok("progfile", 65);
  
    // msgget creates a message queue
    // and returns identifier
    msgid = msgget(key, 0666 | IPC_CREAT);
  
    // msgrcv to receive message
    msgrcv(msgid, &message;, sizeof(message), 1, 0);
  
    // display the message
    printf("Data Received is : %s \n", 
                    message.mesg_text);
  
    // to destroy the message queue
    msgctl(msgid, IPC_RMID, NULL);
  
    return 0;
}


Output: 
 

 



Similar Reads

Message based Communication in IPC (inter process communication)
Prerequisites - Cloud computing, Load balancing in Cloud Computing, Inter-process Communication In the development of models and technologies, message abstraction is a necessary aspect that enables distributed computing. Distributed system is defined as a system in which components reside at networked communication and synchronise its functions onl
5 min read
Difference between Shared Memory Model and Message Passing Model in IPC
Inter-Process Communication (IPC) is a critical aspect of modern operating systems, enabling processes to exchange data and synchronize their actions. Two primary models for IPC are the Shared Memory Model and the Message Passing Model. In the modern operating system, the Inter-Process Communication (IPC) is a very important element. It enables som
4 min read
Difference between Pipes and Message Queues
Pipes: Unix system uses pipes, to establish inter process communication. A pipe provides an unidirectional flow of data. A pipe is created using the pipe() function. Syntax: #include int pipe(int fd); A pipe ()function returns two file descriptors, fd[O] and fd[1]. The fd[0] is open for reading from and fd[1] is open for writing to the pipe. The da
3 min read
IPC technique PIPES
Pipes are a type of IPC (Inter-Process Communication) technique that allows two or more processes to communicate with each other by creating a unidirectional or bidirectional channel between them. A pipe is a virtual communication channel that allows data to be transferred between processes, either one-way or two-way. Pipes can be implemented using
4 min read
IPC through shared memory
Inter Process Communication through shared memory is a concept where two or more process can access the common memory and communication is done via this shared memory where changes made by one process can be viewed by another process. The problem with pipes, fifo and message queue – is that for two process to exchange information. The information h
3 min read
Inter Process Communication (IPC)
Processes can coordinate and interact with one another using a method called inter-process communication (IPC) . Through facilitating process collaboration, it significantly contributes to improving the effectiveness, modularity, and ease of software systems. Types of Process Independent process Co-operating process An independent process is not af
15 min read
Types of Scheduling Queues
As for the concept of computer systems, scheduling queues are among the chief tools defining the execution of processes or threads. These queues are used to reference numerous processes and to be able to differentiate between the executions of these processes. Different types of queues are there, each designed for use in certain situations and, eac
6 min read
Message encryption and decryption using UDP server
The process of message encryption and decryption during client-server communication using UDP server is as follows: The client requests the server with a file name.The corresponding file is opened by the server and sends the file using datagram socket.The sender sends the encrypted text (Xoring) with a fixed length key.The receiver receives the enc
3 min read
Message Passing in Java
What is message passing and why it is used? Message Passing in terms of computers is communication between processes. It is a form of communication used in object-oriented programming as well as parallel programming. Message passing in Java is like sending an object i.e. message from one thread to another thread. It is used when threads do not have
3 min read
Message Passing Model of Process Communication
So message passing means how a message can be sent from one end to the other end. Either it may be a client-server model or it may be from one node to another node. The formal model for distributed message passing has two timing models one is synchronous and the other is asynchronous. The fundamental points of message passing are: In message-passin
3 min read
Print colored message with different fonts and sizes in C
In C/C++ we can use graphics.h header file for creation of programs which uses graphical functions like creating different objects, setting the color of text, printing messages in different fonts and size, changing the background of our output console and much more. Here we will create a program which will print message ("geeks") in colored form in
2 min read
Count number of unique Triangles using STL | Set 1 (Using set)
We are given n triangles along with length of their three sides as a,b,c. Now we need to count number of unique triangles out of these n given triangles. Two triangles are different from one another if they have at least one of the sides different.Example: Input: arr[] = {{1, 2, 2}, {4, 5, 6}, {4, 5, 6} Output: 2 Input: arr[] = {{4, 5, 6}, {6, 5, 4
3 min read
How to print % using printf()?
Here is the standard prototype of printf function in C: int printf(const char *format, ...); The format string is composed of zero or more directives: ordinary characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of argument (and it is an error if insufficiently many arguments are given). The char
1 min read
Print "Even" or "Odd" without using conditional statement
Write a program that accepts a number from the user and prints "Even" if the entered number is even and prints "Odd" if the number is odd. You are not allowed to use any comparison (==, &lt;,&gt;,...etc) or conditional statements (if, else, switch, ternary operator,. Etc). Method 1 Below is a tricky code can be used to print "Even" or "Odd" accordi
4 min read
Count the number of objects using Static member function
Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun
2 min read
C program to copy string without using strcpy() function
strcpy is a C standard library function that copies a string from one location to another. It is defined in the string.h header file. We can use the inbuilt strcpy() function to copy one string to another but here, this program copies the content of one string to another manually without using strcpy() function. Methods to Copy String without using
3 min read
Guess Game using rand() and srand() in C
Using srand() and rand() function in C, a simple but interesting game can be made. This game is called "Guess Game" . Rules of the Game : There are three holes . A rat is hidden in one of those three holes.The Rat shuffles its position every time.You have to guess the hole in which the Rat is hidden among the three holes.The hole in which Rat is pr
3 min read
Creating child process using fork() in Python
Create a child process and display process id of both parent and child process. Fork system call use for creates a new process, which is called child process, which runs concurrently with process (which process called system call fork) and this process is called parent process. After a new child process created, both processes will execute the next
2 min read
Print 1 to 100 without loop using Goto and Recursive-main
Our task is to print all numbers from 1 to 100 without using a loop. There are many ways to print numbers from 1 to 100 without using a loop. Two of them are the goto statement and the recursive main. Print numbers from 1 to 100 Using Goto statement Follow the steps mentioned below to implement the goto statement: declare variable i of value 0decla
5 min read
Sum of array using pointer arithmetic
Given an array, write a program to find the sum of array using pointers arithmetic. In this program we make use of * operator . The * (asterisk) operator denotes the value of variable. The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer . sum() functi
2 min read
fork() to execute processes from bottom to up using wait()
fork() system call is used to create a process generally known as child process and the process that created it is known as parent process. Now, all the processes that are created using fork() runs concurrently. But what if we want the last process created to execute first and in this manner bottom to up execution such that parent process executes
3 min read
Reader-Writers solution using Monitors
Prerequisite - Process Synchronization, Monitors, Readers-Writers Problem Considering a shared Database our objectives are: Readers can access database only when there are no writers.Writers can access database only when there are no readers or writers.Only one thread can manipulate the state variables at a time. What is the Reader-Writers problem?
4 min read
Linear search using Multi-threading
Given a large file of integers, search for a particular element in it using multi-threading. Examples: Input : 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220Output :if key = 20Key element foundInput :1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220Output :if key = 202Key not presentPrerequisite : Multi-threading Recommen
6 min read
Sort an array using socket programming in C
Given an array of unsorted positive integer, sort the given array using the Socket programming . Examples: Input : 4 5 6 1 8 2 7 9 3 0 Output :0 1 2 3 4 5 6 7 8 9 Input : 9 8 1 4 0 Output : 0 1 4 8 9 Compile these files using gcc command (gcc client.c -o client and gcc server.c -o server). Run the program using ./server and ./client (Please note :
3 min read
Reverse a string in C/C++ using Client Server model
This article describes a Client and Server setup where a Client connects, sends a string to server and the server shows the original string and sends reversed string to client using socket connection. Prerequisite : Socket Programming Examples: Input : welcome Output :emoclew Input :geeks for geeks Output :skeeg rof skeeg Explanation In this, first
3 min read
Print 1 2 3 infinitely using threads in C
Print 1 2 3 infinitely using thread. Create three threads viz T1, T2, and T3 such that those should print 1 2 3 sequence infinitely. Examples : Output :1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 ...... Prerequisite : Threads in C Approach : Start an infinite loop and initialize a variable 'done' to 1. Now, check for the value of done is not equal to 1. If it is
2 min read
Determinant of N x N matrix using multi-threading
Given a matrix of N x N, task is to find the determinant of the matrix using multi-threading. Examples : Input : mat = {{0, 4, 0, -3}, {1, 1, 5, 2}, {1, -2, 0, 6}, { 3, 0, 0, 1}} Output : -250 Input : mat = {{1, 0, 2, -1}, {3, 0, 0, 5}, {2, 1, 4, -3}, {1, 0, 5, 0}} Output: 30 Approach : It is known that finding the determinant of a matrix can be ve
6 min read
Communication between two process using signals in C
Prerequisite : C signal handling In this post, the communication between child and parent processes is done using kill() and signal(), fork() system call. fork() creates the child process from the parent. The pid can be checked to decide whether it is the child (if pid == 0) or the parent (pid = child process id).The parent can then send messages t
3 min read
Print numbers in sequence using thread synchronization
The problem is to synchronize n number of threads using pthread library. The idea is take thread count and print 1 in first thread, print 2 in second thread, print 3 in third thread, ..... print n in nth thread and again repeat from thread 1 infinitely. Prerequisite : Multithreading Examples : Input : Thread count Output : 1 2 3 ... thread count 1
2 min read
Image Compression using Huffman Coding
Huffman coding is one of the basic compression methods, that have proven useful in image and video compression standards. When applying Huffman encoding technique on an Image, the source symbols can be either pixel intensities of the Image, or the output of an intensity mapping function. Prerequisites : Huffman Coding | File Handling The first step
15+ min read