Monday, September 29, 2025
HomeLanguagesCreating child process using fork() in Python

Creating child process using fork() in Python

Create a child process and display process id of both parent and child process.

Fork system call use for creates a new process, which is called child process, which runs concurrently with process (which process called system call fork) and this process is called parent process. After a new child process created, both processes will execute the next instruction following the fork() system call.

Library used :
os : The OS module in Python provides a way of using operating system dependent functionality. The functions that the OS module provides allows you to interface with the underlying operating system that Python is running on; be that Windows, Mac or Linux. It can be imported as –

import os

System Call Used :

  • fork() : fork() is an operation whereby a process creates a copy of itself. It is usually a system call, implemented in the kernel.
  • getpid() : getpid() returns the process ID (PID) of the calling process.
  • Below is Python program implementing above :




    # Python code to create child process 
    import os
      
    def parent_child():
        n = os.fork()
      
        # n greater than 0  means parent process
        if n > 0:
            print("Parent process and id is : ", os.getpid())
      
        # n equals to 0 means child process
        else:
            print("Child process and id is : ", os.getpid())
              
    # Driver code
    parent_child()

    
    

    Output :

    Child process and id is :  32523
    Parent process and id is :  32524
    

    Note : Output can vary time to time, machine to machine or process to process.

    RELATED ARTICLES

    Most Popular

    Dominic
    32324 POSTS0 COMMENTS
    Milvus
    84 POSTS0 COMMENTS
    Nango Kala
    6695 POSTS0 COMMENTS
    Nicole Veronica
    11860 POSTS0 COMMENTS
    Nokonwaba Nkukhwana
    11918 POSTS0 COMMENTS
    Shaida Kate Naidoo
    6807 POSTS0 COMMENTS
    Ted Musemwa
    7073 POSTS0 COMMENTS
    Thapelo Manthata
    6763 POSTS0 COMMENTS
    Umr Jansen
    6771 POSTS0 COMMENTS