Python | os.fork() method

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 represnts
# 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 occured while
# using os.fork() method
# OSError will be raised

chevron_right


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


My Personal Notes arrow_drop_up

self motivated and passionate programmer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.