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.
# Signatureos.fork()
This method doesn't take any argument value.
This method returns an integer value.
fork()
is successfully called in the parent process.fork()
is successfully called in the child process. fork()
call.# 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())
os.fork()
to create a child process in the main parent process.pid > 0
means fork()
is called in the parent process.pid < 0
means fork()
is unable to create a child process.pid = 0
means fork()
is called in a child process.pid > 0
, fork()
was called in the parent process. We print the parent and child process IDs.pid < 0
, fork()
is unable to create a new process.pid = 0
, fork()
is called in the child process. We print child and parent process IDs.