The Wayback Machine - https://web.archive.org/web/20240906015858/https://www.geeksforgeeks.org/inter-process-communication-ipc/
Open In App

Inter Process Communication (IPC)

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 affected by the execution of other processes while a co-operating process can be affected by other executing processes. Though one can think that those processes, which are running independently, will execute very efficiently, in reality, there are many situations when cooperative nature can be utilized for increasing computational speed, convenience, and modularity. Inter-process communication (IPC) is a mechanism that allows processes to communicate with each other and synchronize their actions. The communication between these processes can be seen as a method of cooperation between them. Processes can communicate with each other through both:
Methods of IPC

  • Shared Memory
  • Message Passing

A deep understanding of Inter-process Communication (IPC) mechanisms is essential for success in exams like GATE, where operating systems and process management are key topics. To strengthen your knowledge and enhance your exam preparation, consider enrolling in the GATE CS Self-Paced Course . This course offers comprehensive coverage of IPC and other essential operating system concepts, providing you with the insights and skills needed to excel in your exams.

Figure 1 below shows a basic structure of communication between processes via the shared memory method and via the message passing method.

An operating system can implement both methods of communication. First, we will discuss the shared memory methods of communication and then message passing. Communication between processes using shared memory requires processes to share some variable, and it completely depends on how the programmer will implement it. One way of communication using shared memory can be imagined like this: Suppose process1 and process2 are executing simultaneously, and they share some resources or use some information from another process. Process1 generates information about certain computations or resources being used and keeps it as a record in shared memory. When process2 needs to use the shared information, it will check in the record stored in shared memory and take note of the information generated by process1 and act accordingly. Processes can use shared memory for extracting information as a record from another process as well as for delivering any specific information to other processes.
Let’s discuss an example of communication between processes using the shared memory method.


Process in memory

i) Shared Memory Method

Ex: Producer-Consumer problem

There are two processes: Producer and Consumer . The producer produces some items and the Consumer consumes that item. The two processes share a common space or memory location known as a buffer where the item produced by the Producer is stored and from which the Consumer consumes the item if needed. There are two versions of this problem: the first one is known as the unbounded buffer problem in which the Producer can keep on producing items and there is no limit on the size of the buffer, the second one is known as the bounded buffer problem in which the Producer can produce up to a certain number of items before it starts waiting for Consumer to consume it. We will discuss the bounded buffer problem. First, the Producer and the Consumer will share some common memory, then the producer will start producing items. If the total produced item is equal to the size of the buffer, the producer will wait to get it consumed by the Consumer. Similarly, the consumer will first check for the availability of the item. If no item is available, the Consumer will wait for the Producer to produce it. If there are items available, Consumer will consume them. The pseudo-code to demonstrate is provided below:

Shared Data Between the two Processes

C
#define buff_max 25
#define mod %

    struct item{

        // different member of the produced data 
        // or consumed data    
        ---------
    }
    
    // An array is needed for holding the items. 
    // This is the shared place which will be  
    // access by both process   
    // item shared_buff [ buff_max ];
     
    // Two variables which will keep track of 
    // the indexes of the items produced by producer 
    // and consumer The free index points to 
    // the next free index. The full index points to 
    // the first full index. 
    int free_index = 0;
    int full_index = 0;
  

Producer Process Code

C
item nextProduced;
    
    while(1){
        
        // check if there is no space 
        // for production.
        // if so keep waiting.
        while((free_index+1) mod buff_max == full_index);
        
        shared_buff[free_index] = nextProduced;
        free_index = (free_index + 1) mod buff_max;
    }

Consumer Process Code

C
item nextConsumed;
    
    while(1){
        
        // check if there is an available 
        // item  for consumption. 
        // if not keep on waiting for 
        // get them produced.
        while((free_index == full_index);
        
        nextConsumed = shared_buff[full_index];
        full_index = (full_index + 1) mod buff_max;
    }

In the above code, the Producer will start producing again when the (free_index+1) mod buff max will be free because if it is not free, this implies that there are still items that can be consumed by the Consumer so there is no need to produce more. Similarly, if free index and full index point to the same index, this implies that there are no items to consume.

Overall C++ Implementation:

C++
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

#define buff_max 25
#define mod %

struct item {
  // different member of the produced data 
  // or consumed data    
  // ---------
};

// An array is needed for holding the items. 
// This is the shared place which will be  
// access by both process   
// item shared_buff[buff_max];

// Two variables which will keep track of 
// the indexes of the items produced by producer 
// and consumer The free index points to 
// the next free index. The full index points to 
// the first full index. 
std::atomic<int> free_index(0);
std::atomic<int> full_index(0);
std::mutex mtx;

void producer() {
  item new_item;
  while (true) {
    // Produce the item
    // ...
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    // Add the item to the buffer
    while (((free_index + 1) mod buff_max) == full_index) {
      // Buffer is full, wait for consumer
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    mtx.lock();
    // Add the item to the buffer
    // shared_buff[free_index] = new_item;
    free_index = (free_index + 1) mod buff_max;
    mtx.unlock();
  }
}

void consumer() {
  item consumed_item;
  while (true) {
    while (free_index == full_index) {
      // Buffer is empty, wait for producer
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    mtx.lock();
    // Consume the item from the buffer
    // consumed_item = shared_buff[full_index];
    full_index = (full_index + 1) mod buff_max;
    mtx.unlock();
    // Consume the item
    // ...
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
  }
}

int main() {
  // Create producer and consumer threads
  std::vector<std::thread> threads;
  threads.emplace_back(producer);
  threads.emplace_back(consumer);

  // Wait for threads to finish
  for (auto& thread : threads) {
    thread.join();
  }

  return 0;
}

Note that the atomic class is used to make sure that the shared variables free_index and full_index are updated atomically. The mutex is used to protect the critical section where the shared buffer is accessed. The sleep_for function is used to simulate the production and consumption of items.

ii) Messaging Passing Method


Now, We will start our discussion of the communication between processes via message passing. In this method, processes communicate with each other without using any kind of shared memory. If two processes p1 and p2 want to communicate with each other, they proceed as follows:

  • Establish a communication link (if a link already exists, no need to establish it again.)
  • Start exchanging messages using basic primitives.
    We need at least two primitives:
    – send (message, destination) or send (message)
    – receive (message, host) or receive (message)


IPC processs


The message size can be of fixed size or of variable size. If it is of fixed size, it is easy for an OS designer but complicated for a programmer and if it is of variable size then it is easy for a programmer but complicated for the OS designer. A standard message can have two parts: header and body. The header part is used for storing message type, destination id, source id, message length, and control information. The control information contains information like what to do if runs out of buffer space, sequence number, priority. Generally, message is sent using FIFO style.

Message Passing Through Communication Link

Direct and Indirect Communication link

Now, We will start our discussion about the methods of implementing communication links. While implementing the link, there are some questions that need to be kept in mind like :

  • How are links established?
  • Can a link be associated with more than two processes?
  • How many links can there be between every pair of communicating processes?
  • What is the capacity of a link? Is the size of a message that the link can accommodate fixed or variable?
  • Is a link unidirectional or bi-directional?


A link has some capacity that determines the number of messages that can reside in it temporarily for which every link has a queue associated with it which can be of zero capacity, bounded capacity, or unbounded capacity. In zero capacity, the sender waits until the receiver informs the sender that it has received the message. In non-zero capacity cases, a process does not know whether a message has been received or not after the send operation. For this, the sender must communicate with the receiver explicitly. Implementation of the link depends on the situation, it can be either a direct communication link or an in-directed communication link.
Direct Communication links are implemented when the processes use a specific process identifier for the communication, but it is hard to identify the sender ahead of time.
For example the print server.
In-direct Communication is done via a shared mailbox (port), which consists of a queue of messages. The sender keeps the message in mailbox and the receiver picks them up.

Synchronous and Asynchronous Message Passing

A process that is blocked is one that is waiting for some event, such as a resource becoming available or the completion of an I/O operation. IPC is possible between the processes on same computer as well as on the processes running on different computer i.e. in networked/distributed system. In both cases, the process may or may not be blocked while sending a message or attempting to receive a message so message passing may be blocking or non-blocking. Blocking is considered synchronous and blocking send means the sender will be blocked until the message is received by receiver. Similarly, blocking receive has the receiver block until a message is available. Non-blocking is considered asynchronous and Non-blocking send has the sender sends the message and continue. Similarly, Non-blocking receive has the receiver receive a valid message or null. After a careful analysis, we can come to a conclusion that for a sender it is more natural to be non-blocking after message passing as there may be a need to send the message to different processes. However, the sender expects acknowledgment from the receiver in case the send fails. Similarly, it is more natural for a receiver to be blocking after issuing the receive as the information from the received message may be used for further execution. At the same time, if the message send keep on failing, the receiver will have to wait indefinitely. That is why we also consider the other possibility of message passing. There are basically three preferred combinations:

  • Blocking send and blocking receive
  • Non-blocking send and Non-blocking receive
  • Non-blocking send and Blocking receive (Mostly used)


In Direct message passing , The process which wants to communicate must explicitly name the recipient or sender of the communication.
e.g. send(p1, message) means send the message to p1.
Similarly, receive(p2, message) means to receive the message from p2.
In this method of communication, the communication link gets established automatically, which can be either unidirectional or bidirectional, but one link can be used between one pair of the sender and receiver and one pair of sender and receiver should not possess more than one pair of links. Symmetry and asymmetry between sending and receiving can also be implemented i.e. either both processes will name each other for sending and receiving the messages or only the sender will name the receiver for sending the message and there is no need for the receiver for naming the sender for receiving the message. The problem with this method of communication is that if the name of one process changes, this method will not work.
In Indirect message passing , processes use mailboxes (also referred to as ports) for sending and receiving messages. Each mailbox has a unique id and processes can communicate only if they share a mailbox. Link established only if processes share a common mailbox and a single link can be associated with many processes. Each pair of processes can share several communication links and these links may be unidirectional or bi-directional. Suppose two processes want to communicate through Indirect message passing, the required operations are: create a mailbox, use this mailbox for sending and receiving messages, then destroy the mailbox. The standard primitives used are: send(A, message) which means send the message to mailbox A. The primitive for the receiving the message also works in the same way e.g. received (A, message) . There is a problem with this mailbox implementation. Suppose there are more than two processes sharing the same mailbox and suppose the process p1 sends a message to the mailbox, which process will be the receiver? This can be solved by either enforcing that only two processes can share a single mailbox or enforcing that only one process is allowed to execute the receive at a given time or select any process randomly and notify the sender about the receiver. A mailbox can be made private to a single sender/receiver pair and can also be shared between multiple sender/receiver pairs. Port is an implementation of such mailbox that can have multiple senders and a single receiver. It is used in client/server applications (in this case the server is the receiver). The port is owned by the receiving process and created by OS on the request of the receiver process and can be destroyed either on request of the same receiver processor when the receiver terminates itself. Enforcing that only one process is allowed to execute the receive can be done using the concept of mutual exclusion. Mutex mailbox is created which is shared by n process. The sender is non-blocking and sends the message. The first process which executes the receive will enter in the critical section and all other processes will be blocking and will wait.
Now, let’s discuss the Producer-Consumer problem using the message passing concept. The producer places items (inside messages) in the mailbox and the consumer can consume an item when at least one message present in the mailbox. The code is given below:

Producer Code

C
void Producer(void){
        
        int item;
        Message m;
        
        while(1){
            
            receive(Consumer, &m);
            item = produce();
            build_message(&m , item ) ;
            send(Consumer, &m);
        }
    }

Consumer Code

C
void Consumer(void){
        
        int item;
        Message m;
        
        while(1){
            
            receive(Producer, &m);
            item = extracted_item();
            send(Producer, &m);
            consume_item(item);
        }
    }

Examples of IPC systems

  • Posix : uses shared memory method.
  • Mach : uses message passing
  • Windows XP : uses message passing using local procedural calls

Communication in Client/Server Architecture

There are various mechanism

  • Pipe
  • Socket
  • Remote Procedural calls (RPCs)


The above three methods will be discussed in later articles as all of them are quite conceptual and deserve their own separate articles.
References:

  • Operating System Concepts by Galvin et al.
  • Lecture notes/ppt of Ariel J. Frank, Bar-Ilan University

Inter-process communication (IPC) is the mechanism through which processes or threads can communicate and exchange data with each other on a computer or across a network. IPC is an important aspect of modern operating systems, as it enables different processes to work together and share resources, leading to increased efficiency and flexibility.

Role of Synchronization in IPC

In IPC, synchronization is essential for controlling access to shared resources and guaranteeing that processes do not conflict with one another. Data consistency is ensured and problems like race situations are avoided with proper synchronization.

Advantages of IPC

  • Enables processes to communicate with each other and share resources, leading to increased efficiency and flexibility.
  • Facilitates coordination between multiple processes, leading to better overall system performance.
  • Allows for the creation of distributed systems that can span multiple computers or networks.
  • Can be used to implement various synchronization and communication protocols, such as semaphores, pipes, and sockets.

Disadvantages of IPC

  • Increases system complexity, making it harder to design, implement, and debug.
  • Can introduce security vulnerabilities, as processes may be able to access or modify data belonging to other processes.
  • Requires careful management of system resources, such as memory and CPU time, to ensure that IPC operations do not degrade overall system performance.
    Can lead to data inconsistencies if multiple processes try to access or modify the same data at the same time.
  • Overall, the advantages of IPC outweigh the disadvantages, as it is a necessary mechanism for modern operating systems and enables processes to work together and share resources in a flexible and efficient manner. However, care must be taken to design and implement IPC systems carefully, in order to avoid potential security vulnerabilities and performance issues.

Conclusion

A fundamental component of contemporary operating systems, IPC allows processes to efficiently coordinate operations, share resources, and communicate. IPC is beneficial for developing adaptable and effective systems, despite its complexity and possible security threats.

Frequently Asked Questions on IPC – FAQs

What is IPC?

Process communication and synchronization are made possible via IPC, which promotes resource sharing and teamwork.

Why is synchronization important in IPC?

Data consistency and conflict avoidance are ensured via synchronization when different processes access common resources.

What are the main methods of IPC?

Message passing and shared memory are the two main techniques. While message passing permits communication without the need for shared data, shared memory permits processes to share data directly.



Previous Article
Next Article

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
IPC using Message Queues
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
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
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
Classless Inter Domain Routing (CIDR)
Classless Inter-Domain Routing (CIDR) is a method of IP address allocation and IP routing that allows for more efficient use of IP addresses. CIDR is based on the idea that IP addresses can be allocated and routed based on their network prefix rather than their class, which was the traditional way of IP address allocation. CIDR addresses are repres
6 min read
Difference Between Process, Parent Process, and Child Process
Running program is a process. From this process, another process can be created. There is a parent-child relationship between the two processes. This can be achieved using a library function called fork(). fork() function splits the running process into two processes, the existing one is known as parent and the new process is known as a child. Here
8 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
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
Process Scheduler : Job and Process Status
When the jobs moves through the system and makes progress, it changes it's states from HOLD to FINISH. When the job is being processed by the job manager and the process manager, it is always in one of these 5 states: HOLD: When a user submits a job and it accepts the job, the job is put on HOLD and placed in a queue. READY: A job is in READY state
2 min read
Difference between Process Image and Multi Thread Process image
1. Process Image : Process image is an executable file required during the execution of any process. It consists of several segments related to the execution of the process. Following are the contents of the process image - 1. Process Control Block 2. Stack 3. Data 4. Code 2. Multi Thread Process Image : Multi thread process image is an executable
2 min read
Process Table and Process Control Block (PCB)
While creating a process, the operating system performs several operations. To identify the processes, it assigns a process identification number (PID) to each process. As the operating system supports multi-programming, it needs to keep track of all the processes. For this task, the process control block (PCB) is used to track the process’s execut
7 min read
Process states and Transitions in a UNIX Process
Process is an instance of a program in execution. A set of processes combined together make a complete program. There are two categories of processes in Unix, namely User processes : They are operated in user mode. Kernel processes : They are operated in kernel mode. Understanding the distinction between user and kernel processes is essential for c
4 min read
How Communication happens using OSI model
The Open System Interconnection (OSI) model is a standard “reference model” created by an International Organization for Standardization (ISO) to describe how software and hardware components involved in network communication divide efforts and interact with each other. The OSI model defines a seven-layer set of functional elements, from physical i
4 min read
Structure of Wireless Communication Link
The Structure of a wireless communication link involves several key components that work together and maintains the connection between the transmitter and the receiver. Every component plays an important role in the proper transmission of data from the transmitter to the receiver. The following block diagram demonstrates the complete structure of t
4 min read
Communication Structure in Operating System
In this article, we'll look at the communication structure of an operating system. It provides an interface between applications and other programs so that users can use them more easily. The hardware/software resources handled by an operating system include memory, keystrokes, disk accesses, CPU cycles, and bandwidth on main communication channels
10 min read
Communication to I/O Devices in Operating System
The foundation of efficient computing rests on robust interaction between users and an operating system through Input/Output (I/O) devices in today's world. The smooth functioning necessitates dependable exchange of data among keyboard/screen/mouse/printers/network adapters facilitated by such intermediary agents. Establishing consistent two-way co
5 min read
Client Server Communication in Operating System
In an Operating System, Client Server Communication refers to the exchange of data and Services among multiple machines or processes. In Client client-server communication System one process or machine acts as a client requesting a service or data, and Another machine or process acts like a server for providing those Services or Data to the client
3 min read
How Transport Layer Security (TLS) Protocols Ensure Secure Communication?
Answer: TLS protocols like SSL/TLS makes sure the secure communication through encryption, authentication with digital certificates, and data integrity checks.Transport Layer Security (TLS) Protocols like SSL/TLS ensure secure communication using below methods: EncryptionTLS uses the encryption algorithms to encrypt data which is transmitted betwee
2 min read
Operating Systems | Process Management | Question 6
Consider the following code fragment: if (fork() == 0) { a = a + 5; printf(&quot;%d,%d\n&quot;, a, &amp;a); } else { a = a –5; printf(&quot;%d, %d\n&quot;, a, &amp;a); } Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE? (A) u = x + 10 and v = y (B) u = x +
2 min read
Operating Systems | Process Management | Question 6
Three concurrent processes X, Y, and Z execute three different code segments that access and update certain shared variables. Process X executes the P operation (i.e., wait) on semaphores a, b and c; process Y executes the P operation on semaphores b, c and d; process Z executes the P operation on semaphores c, d, and a before entering the respecti
2 min read
Operating Systems | Process Management | Question 6
A shared variable x, initialized to zero, is operated on by four concurrent processes W, X, Y, Z as follows. Each of the processes W and X reads x from memory, increments by one, stores it to memory, and then terminates. Each of the processes Y and Z reads x from memory, decrements by two, stores it to memory, and then terminates. Each process befo
2 min read
Process-Based and Thread-Based Multitasking
Multitasking operating system is an operating system that gives you the perception of two or more tasks/jobs/processes running simultaneously. It does this by dividing system resources amongst these tasks/jobs/processes and switching between the tasks/jobs/processes while they are executing over and over again. The CPU processes only one task at a
2 min read
Union process in DFA
Prerequisite - Designing finite automata To perform the union operation on two deterministic finite automata (DFAs), the following steps can be taken: Create a new DFA with a new set of states, consisting of all the states from both original DFAs.Define the initial state of the new DFA to be the tuple (q1, q2), where q1 and q2 are the initial state
5 min read
Concatenation process in DFA
Prerequisite - Designing finite automata Designing a DFA for the set of string over {a, b} such that string of the language start with "a" and end with "b". There two desired language will be formed: L1 = {a, aab, aabab, .......} L2 = {b, bbab, bbabab, .......} In L1, starting element is "a" and in L2, ending element is b. State Transition Diagram
2 min read
Get/Set process resource limits in C
The getrlimit() and setrlimit() system calls can be used to get and set the resource limits such as files, CPU, memory etc. associated with a process. Each resource has an associated soft and hard limit. soft limit: The soft limit is the actual limit enforced by the kernel for the corresponding resource. hard limit: The hard limit acts as a ceiling
3 min read
Complementation process in DFA
Prerequisite – Design a Finite automata Suppose we have a DFA that is defined by ( Q, [Tex]\Sigma [/Tex], [Tex]\delta [/Tex], q0, F ) and it accepts the language L1. Then, the DFA which accepts the language L2 where L2 = ̅L1', will be defined as below: ( Q, [Tex]\Sigma[/Tex], [Tex]\delta[/Tex], q0, Q-F ) The complement of a DFA can be obtained by m
2 min read
Process Scheduler : PCBs and Queueing
When the job scheduler accepts a job, it creates the job's PCB (Process Control Blocks) and updates it throughout the execution. These PCBs, and not the jobs, are linked to form the queues and are used to track the respective jobs. Note: The PCB store all of the data about the job being processed, like it's progress in the system. This data is need
1 min read
Two State Process Model in Operating System
Pre-requisite: States of a Process in Operating Systems The process in an operating system passes from different states starting from its formation to its completion. A process consists of program data and its associated data and a process control block (PCB). A process may change its state because of the following events like I/O requests, interru
3 min read
Formation Of Process from Program
Process: A Process is a program in execution is called as Program. But the conversion of a program into process involves various stages which are clearly defined in this article. Further more after the program is converted into the process memory has to be allocated to these process in the main memory and these memory allocations are handled by O.S
5 min read