Creating child process using fork() in Python

PythonProgrammingServer Side Programming

Our task is to create a child process and display process id of both parent and child process using fork() function in Python.

When we use fork(), it creates a copy of itself, it is a very important aspect of LINUX, UNIX. fork() is mainly applicable for multithreading environment that means the execution of the thread is duplicated created a child thread from a parent thread. When there is an error, the method will return a negative value and for the child process, it returns 0, Otherwise, it returns positive value that means we are in the parent process.

The fork() module can be used from the os module or from Pseudo terminal module called pty. So we should import os or pty for it.

The fork() is used to create a process, it has no argument and its return the process ID. The main reason for using fork() to create a new process which becomes the child process of the caller. When a new child process is created, both processes will execute the next instruction.

The return value of fork() we can understand which process we are when return 0 that means we are in the child process and if return positive value that means we are in the parent process and return negative value means that some error occurred.

Example code

import os
   def parentchild():
      n = os.fork()
   if n > 0:
      print("Parent process : ", os.getpid())
   else:
      print("Child proces : ", os.getpid())
# Driver code
parentchild()

Output

Parent process : 8023
Child process : 8024
$

The Pseudo-terminal utility module pty is defined to handle pseudo-terminal concepts. Using this we can start another process, and also can read or write from controlling terminal using programs.

This module is highly platform oriented. We should use UNIX systems to perform these operations.

Example code

import pty, os
   def process_parent_child():
      (process_id, fd) = pty.fork()
   print("The Process ID for the Current process is: " + str(os.getpid()))
   print("The Process ID for the Child process is: " + str(process_id))
process_parent_child()

Output

The Process ID for the Current process is: 12508
The Process ID for the Child process is: 12509
raja
Published on 14-Nov-2018 12:33:42
Advertisements