ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Operating Systems
    COMP3142
    Progress0 / 34 topics
    Topics
    1. Operating Systems Basics2. System Calls3. Process Concept and Scheduling4. Interprocess Communication5. Multithreaded Programming6. Multithreading Models7. Threading Issues8. Process Scheduling Algorithms9. Thread Scheduling10. Multiple-Processor Scheduling11. Synchronization12. Critical Section13. Synchronization Hardware14. Synchronization Problems15. Deadlocks16. Detecting and Recovering from Deadlocks17. Memory Management18. Swapping19. Contiguous Memory Allocation20. Segmentation and Paging21. Virtual Memory Management22. Demand Paging23. Thrashing24. Memory-Mapped Files25. File Systems26. File Concept27. Directory and Disk Structure28. Directory Implementation29. Free Space Management30. Disk Structure and Scheduling31. Swap Space Management32. System Protection33. Virtual Machines34. Operating System Security
    COMP3142›Interprocess Communication
    Operating SystemsTopic 4 of 34

    Interprocess Communication

    7 minread
    1,242words
    Intermediatelevel

    Interprocess Communication (IPC)

    Interprocess Communication (IPC) refers to the mechanisms provided by the operating system that allow processes to communicate with each other, either within the same system or across different systems (in distributed environments). Since processes run independently in their own address spaces, they need a way to share data, synchronize their actions, or send messages to each other in order to perform coordinated tasks.

    IPC is crucial for many applications, especially in multitasking environments where different processes might need to collaborate or share data. Various IPC mechanisms exist, each with its specific use cases, performance characteristics, and complexities.


    1. Types of Interprocess Communication

    IPC can be broadly classified into two types based on how communication occurs between processes:

    • Message Passing
    • Shared Memory

    A. Message Passing

    In message passing, processes communicate by sending and receiving messages. These messages can be either synchronous or asynchronous.

    • Synchronous Communication: The sender is blocked until the receiver acknowledges the message. Both processes are in sync.
    • Asynchronous Communication: The sender sends a message and continues execution without waiting for the receiver to acknowledge the message.
    Types of Message Passing:
    1. Direct Communication:

      • The sender and receiver must be explicitly specified.
      • Each process needs to know the address of the other.
      • Example: send(receiver, message) and receive(sender, message).
      • Advantages: Simple and direct.
      • Disadvantages: More overhead, especially when processes are dynamically created or destroyed.
    2. Indirect Communication:

      • The message is sent to a mailbox or message queue, and the receiver retrieves it.
      • Processes don’t need to know each other’s identity, just the mailbox or queue.
      • Example: A process sends a message to a message queue, and the receiver takes it from the queue.
      • Advantages: More flexible; decouples the processes.
      • Disadvantages: Requires additional resources to manage the message queues or mailboxes.
    Message Passing Mechanisms:
    • Pipes: Unidirectional communication channel between two processes.

      • Named Pipes (FIFOs): These allow unrelated processes to communicate by reading and writing to a named pipe.
    • Sockets: A more complex form of message passing, often used for communication between processes over a network. Sockets support both stream-based (TCP) and datagram-based (UDP) communication.

    • Message Queues: Allow processes to exchange messages, which are stored in queues. The system handles synchronization and buffering, and the messages can be retrieved by processes in the order they were sent.

    B. Shared Memory

    Shared memory allows two or more processes to share a region of memory. One process writes to the memory region, while others can read from it. This is typically much faster than message passing because it avoids the overhead of copying data between processes.

    Key Features of Shared Memory:
    • Fast Communication: Since the data is already in memory, processes can access it directly.
    • Synchronization Required: Since multiple processes can access shared memory simultaneously, there is a need for synchronization mechanisms to avoid data corruption.
    Common Mechanisms for Synchronization in Shared Memory:
    1. Semaphores: A semaphore is a signaling mechanism used to synchronize access to shared resources. It helps in managing mutual exclusion and synchronizing processes to avoid race conditions.

      • Binary Semaphores: Used for mutual exclusion, ensuring only one process accesses the critical section at a time.
      • Counting Semaphores: Used for more complex synchronization, such as managing a set of resources.
    2. Mutexes (Mutual Exclusion Locks): Similar to semaphores but typically used in situations where only one process can enter a critical section of code at a time. A mutex provides a mechanism for locking and unlocking shared resources.

    3. Condition Variables: These are used to allow processes to wait for a certain condition to be met before continuing execution. They are often used in conjunction with mutexes.

    4. Memory Mapped Files: Shared memory can also be mapped to a file in memory, allowing multiple processes to access and modify the data as though it were part of their memory space.


    2. Common IPC Mechanisms

    There are several ways to implement IPC, each suited for different situations. Below are some of the most common mechanisms:

    1. Pipes

    A pipe is a unidirectional communication channel used between two processes. Pipes are usually used for communication between related processes (parent-child). In Unix-like systems, the pipe() system call creates a pipe.

    • Anonymous Pipes: Typically used for communication between related processes (e.g., a parent and child process).
    • Named Pipes (FIFOs): These allow communication between any processes, even if they are not related. Named pipes appear as special files in the file system and can be accessed by any process.
    Example:
    #include <stdio.h>
    #include <unistd.h>
    
    int main() {
        int pipe_fd[2];
        pipe(pipe_fd);  // Create a pipe
        pid_t pid = fork(); // Create a child process
        
        if (pid == 0) {
            // Child Process: Writes to the pipe
            close(pipe_fd[0]);
            write(pipe_fd[1], "Hello, Parent!", 15);
            close(pipe_fd[1]);
        } else {
            // Parent Process: Reads from the pipe
            close(pipe_fd[1]);
            char buffer[20];
            read(pipe_fd[0], buffer, sizeof(buffer));
            printf("Received from child: %s\n", buffer);
            close(pipe_fd[0]);
        }
        
        return 0;
    }
    

    2. Message Queues

    A message queue allows processes to send and receive messages in a queue-like structure. It can store messages until the receiver retrieves them.

    • Advantages: Asynchronous communication, decoupling of sender and receiver.
    • Disadvantages: Can introduce overhead, especially with larger message queues.
    Example:

    Message queues can be created and managed using system calls like msgget(), msgsnd(), and msgrcv() in Unix-like systems.

    3. Shared Memory

    As mentioned earlier, shared memory enables processes to communicate by accessing a common memory space. This is one of the fastest IPC mechanisms, as it avoids the need to copy data between processes. However, it requires synchronization mechanisms to prevent conflicts and ensure data consistency.

    Example:

    In Unix-like systems, shmget() creates a shared memory segment, and shmat() attaches it to the process's address space. Synchronization is done using semaphores or mutexes.

    4. Sockets

    Sockets provide a mechanism for IPC that allows processes to communicate over a network or within the same system. Sockets can be either stream sockets (TCP) or datagram sockets (UDP), and they provide bidirectional communication.

    • Stream Sockets (TCP): Used for reliable, connection-oriented communication between processes.
    • Datagram Sockets (UDP): Used for connectionless, unreliable communication between processes.
    Example:
    // Server code snippet using TCP sockets
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    listen(sockfd, 5);
    int client_sock = accept(sockfd, (struct sockaddr *)&client_addr, &client_addr_len);
    send(client_sock, "Hello, Client!", 14, 0);
    
    // Client code snippet using TCP sockets
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    char buffer[1024];
    recv(sockfd, buffer, sizeof(buffer), 0);
    printf("Received from server: %s\n", buffer);
    

    3. Choosing IPC Mechanisms

    Choosing the appropriate IPC mechanism depends on various factors:

    • Speed: Shared memory is faster compared to message passing, but requires synchronization.
    • Simplicity: Message queues and pipes are simpler to implement compared to shared memory.
    • Resource Sharing: Shared memory is suitable when processes need to share large amounts of data.
    • Synchronization: If synchronization is required, semaphores or mutexes are necessary when using shared memory.

    4. Conclusion

    Interprocess communication (IPC) is crucial for modern operating systems, enabling processes to coordinate and communicate effectively. It provides various mechanisms like message passing, shared memory, pipes, sockets, and message queues, each suited for different scenarios. By understanding the strengths and weaknesses of these mechanisms, developers can choose the most efficient method for their applications' needs, ensuring better performance, synchronization, and resource management in multitasking environments.

    Previous topic 3
    Process Concept and Scheduling
    Next topic 5
    Multithreaded Programming

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,242
      Code examples0
      DifficultyIntermediate