
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to communicate between parent and child process using the pipe.
Inter-process communication (IPC) is essential, When multiple processes need to share the data and work together. In Python, multiprocessing module provides various IPC mechanisms, Out of which one is the pipe.
The pipe allows the data to be transferred from one process to another in a two-way (duplex) or one-way mode. It is useful when a parent process creates a child process and want them to exchange messages or data.
Python multiprocessing.Pipe() Method
The multiprocessing.Pipe() is a method in the Python multiprocessing module that return the pair of connection objects connected by a pipe. This pipe can be used to send and receive data between the two processes.
Syntax
Following is the syntax of Python multiprocessing.Pipe() method -
multiprocessing.Pipe(duplex=True)
Example 1
Let's look at the following example, where we are going to send the string message from the parent process to the child process.
import multiprocessing def demo(conn): x = conn.recv() print(" ", x) if __name__ == "__main__": a, b = multiprocessing.Pipe() result = multiprocessing.Process(target=demo, args=(b,)) result.start() a.send("Welcome to TutorialsPoint") result.join()
The output of the above program is as follows -
Welcome to TutorialsPoint
Example 2
Consider the another scenario, where both the parent and child exchange the using the duplex pipe (duplex=True).
import multiprocessing def demo(y): y.send("Have a nice day.!") x = y.recv() print("Child received:", x) if __name__ == "__main__": a, b = multiprocessing.Pipe(duplex=True) result = multiprocessing.Process(target=demo, args=(b,)) result.start() print("Parent received:", a.recv()) a.send("Same to you") result.join()
The following is the output of the above program -
Parent received: Have a nice day.! Child received: Same to you