Python os.fork() – Create a child process

Python os.fork()

Python All functions in the os module raise OSError if the filename or path is invalid or inaccessible, or if other arguments are of the correct type but not accepted by the operating system.

os.fork() is used to create a child process. This method works by calling the underlying OS function fork(). This method returns 0 in the child process and the child’s process ID in the parent process.

Note: The os.fork() method is only available on UNIX platforms.

Syntax: os.fork()

Parameters: None

Return Type: This method returns an integer representing the child process id in the parent process, or 0 in the child process.

Example 1

Use the os.fork() method to create a child process

# Python program to explain os.fork() method
  
# importing os module
import os
  
  
#Create a child process
# using os.fork() method
pid = os.fork()
  
# pid greater than 0 represents
# the parent process
if pid > 0 :
Print("I am parent process:")
Print("Process ID:", os.getpid())
Print("Child's process ID:", pid)
  
# pid equal to 0 represents
# the created child process
else :
Print("nI am child process:")
Print("Process ID:", os.getpid())
Print("Parent's process ID:", os.getppid())
  
  
# If any error occurred while
# using os.fork() method
# OSError will be raised

Output:

I am Parent process
Process ID: 10793
Child's process ID: 10794

I am child process
Process ID: 10794
Parent's process ID: 10793

Leave a Reply

Your email address will not be published. Required fields are marked *