What is the os.fork() method in Python?
Overview
This os.fork() method in Python provides the implementation of the fork() system, which creates a child or a forked process. Calling fork() results in the creation of an exact copy of the parent process.
An OSError error may occur during the fork() execution due to multiple reasons, like an inaccessible or invalid file path or names, etc.
Syntax
# Signatureos.fork()
Parameters
This method doesn't take any argument value.
Return value
This method returns an integer value.
> 0: It returns greater than zero valule whenpid process id fork()is successfully called in the parent process.- 0: It returns zero when
fork()is successfully called in the child process. - -1: It returns negative one upon unsuccessful
fork()call.
Code
# Program to test fork() methodimport os# Creating child process# In main parent threadpid = os.fork()# It is a parent process when fork() returns pid > 0if pid > 0 :print("Parent process here:")print("Process ID:", os.getpid())print("Child process ID:", pid)if pid < 0: # pid is -1 means unable to create processprint("Unable to create child process")else: # fork() return value 0 meaning it was called in a child processprint("Child process here:")print("Process ID:", os.getpid())print("Parent process ID:", os.getppid())
Explanation
- Line 5: We invoke
os.fork()to create a child process in the main parent process. pid > 0meansfork()is called in the parent process.pid < 0meansfork()is unable to create a child process.pid = 0meansfork()is called in a child process.- Line 7: If
pid > 0,fork()was called in the parent process. We print the parent and child process IDs. - Line 11: If
pid < 0,fork()is unable to create a new process.
- Line 13: If
pid = 0,fork()is called in the child process. We print child and parent process IDs.