Process forking is the traditional method of parallelizing work, especially in *nix operating systems. When a program is forked, the OS simply makes a new copy of the original program, including its memory state, and proceeds to run the two versions of the program simultaneously. Naturally, the copied program can have its own forks, creating a hierarchy of the original, parent process, with numerous children and grandchildren copies. If the parent program is killed, the child processes can still operate normally.
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 accessfork()
:
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...