In operating systems, a pipe is used for inter-process communication. It is a way of passing information from one process to another.
os module provides functionality to interact with the operating system in Python.
os.pipe() Function to Create a Pipe in Python2
os.pipe() function returns two file descriptors; one for writing data to the pipe and one for reading data written to the pipe. We will create a pipe to pass information between two processes.
import os r, w = os.pipe() p_id = os.fork() if p_id: os.close(w) r = os.fdopen(r) print ("Parent process reading data from the pipe") data = r.read() print ("data =", data) else: os.close(r) w = os.fdopen(w, 'w') print ("Child writing data to the pipe") w.write("data written by the child") w.close()
The child process writes some data to the pipe using the
w file descriptor, and the parent process reads the data written to the pipe with the
r file descriptor.
Child writing data to the pipe Parent process reading data from the pipe data = data written by the child
The pipe only allows one operation at a time. So, while reading data from it, we have to close the
w file descriptor, and while writing data, we have to close the
r file descriptor with the
The above code works fine on Linux but raises exceptions while running on Windows because of the incompatibility of the