+

Python | os.fork () method

All functions in the os module raise OSError for invalid or unreachable file names and paths or other arguments that are of the correct type but are not accepted by the operating system.

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

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

Syntax: os.fork ()

Parameter: No parameter is required

Return Type: This method returns an integer value representing child`s process id in the parent process while 0 in the child process.

Code: using the os.fork () method to create a child process

# Python program to explain the os.fork () method

 
# import of the os module

import os

 < / p>

 
# Create a child process
# using the os.fork () method

pid = os.fork ()

 
# pid greater than 0 represents
# parent process

if pid & gt;  0 :

print ( "I am parent process:" )

  print ( "Process ID:" , os.getpid ())

print ( "Child`s process ID : " , pid)

  
# pid equals 0 represnts
# created child process

else :

print ( "I am child process:" )

print ( "Process ID:" , os.getpid ())

print ( "Parent`s process ID:" , os.getppid ())

 

 
# If in time of any error
# using the os.fork () method
# OSError will be raised

Exit:

 I am Parent process Process ID: 10793 Child`s process ID: 10794 I am child process Process ID: 10794 Parent`s process ID: 10793 
Get Solution for free from DataCamp guru