Open In App

Python | os.fork() method

Last Updated : 11 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. 

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

Note: os.fork() method is available only 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: Use of os.fork() method to create a child process  

Python3




# 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

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads