Inter-Process Communication Using Pipes

 

Inter-Process Communication Using Pipes


1️⃣ What is a Pipe?

A pipe is a unidirectional communication channel that allows one process to write data and another process to read data.

  • Created using the system call:

pipe(int fd[2]);
EndDescription
fd[0]Read end
fd[1]Write end

2️⃣ When are Pipes Used?

  • Communication between parent and child processes

  • Data flows in one direction

  • Used in commands like:

ls | wc

3️⃣ How IPC Using Pipe Works

  1. Parent creates a pipe

  2. Parent forks a child

  3. Child inherits the pipe

  4. One process writes data

  5. Other process reads data


4️⃣ Important System Calls Used

System CallPurpose
pipe()        Creates pipe
fork()        Creates child process
write()        Writes to pipe
read()        Reads from pipe
close()        Closes unused pipe ends

5️⃣ Simple Example: Parent Writes, Child Reads

🔹 Program Explanation

  • Parent sends a message to child

  • Child reads and prints the message


6️⃣ C Program: IPC Using Pipe

#include <stdio.h> #include <unistd.h> #include <string.h> int main() { int fd[2]; pid_t pid; char message[] = "Hello from parent process"; char buffer[100]; // Create pipe if (pipe(fd) == -1) { perror("pipe"); return 1; } // Create child process pid = fork(); if (pid < 0) { perror("fork"); return 1; } // Child process if (pid == 0) { close(fd[1]); // Close write end read(fd[0], buffer, sizeof(buffer)); printf("Child received: %s\n", buffer); close(fd[0]); } // Parent process else { close(fd[0]); // Close read end write(fd[1], message, strlen(message) + 1); close(fd[1]); } return 0; }

7️⃣ Sample Output

Child received: Hello from parent process

8️⃣ Key Points to Remember 

  • Pipes are unidirectional

  • Used for related processes

  • Child inherits pipe descriptors

  • Must close unused ends to avoid blocking

Comments

Popular posts from this blog

Operating Systems OS Lab PCCSL407 Semester 4 KTU BTech CS 2024 Scheme - Dr Binu V P

Exploring the /proc file system

ps command