In Python, to fork a process, all you have to do is import the os module and invoke the fork() function. The following example creates a simple parent/child process forking program:
- Import the os module, necessary to access fork():
import os
- Define the child process:
def child(): print("Child {} calling".format(os.getpid())) os._exit(0)
- Create the parent process:
def parent():
for i in range(10):
newchild = os.fork()
if newchild == 0:
child()
else:
print("Parent {parent} calling. Creating child {child}".format(parent=os.getpid(), child=newchild))
i += 1