An easy way to create a child process in Python

Python Methods and Functions

Using fork &this is the easiest way to create a child process .fork () is part of the Python standard OS library.

Here we solve this problem with pipe (). To transfer information from one process to another, pipe () is used. For bidirectional communication, you can use two pipes, one for each direction, because pipe () is unidirectional.


 Step 1: file descriptors r, w for reading and writing. Step 2: Create a process using the fork. Step 3: if process id is 0 then create a child process. Step 4: else create parent process. 

Sample code

 import os def parentchild (cwrites): r, w = os.pipe () pid = os .fork () if pid: os.close (w) r = os.fdopen (r) print ("Parent is reading") str = () print ("Parent reads =", str) else: os. close (r) w = os.fdopen (w, 'w') print (" Child is writing ") w.write (cwrites) print (" Child writes = ", cwrites) w.close () # Driver code cwrites = "Python Program" parentchild (cwrites) 


 Chil d is writing Child writes = Python Program Parent is reading Parent reads = Python Program 

Get Solution for free from DataCamp guru