English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Creating child processes using fork() in Python

Our task is to create a child process and usefork()The function in Python displays the process ID of the parent process and child process.

When usedfork()It will create its own copy, which is an important aspect of LINUX and UNIX.fork()Mainly applicable to a multithreading environment, which means that the child threads created from the parent thread will repeat the execution of the thread. When an error occurs, this method will return a negative value, for child processes, this method will return 0, otherwise, it will return a positive value, which means we are in the parent process.

Thefork()The module can be called from the OS module or from the pseudo-terminal module called PTY. Therefore, we should import os or pty for this.

tofork()Used to create a process with no parameters and return the process ID. Usedfork()The main reason to create a new process (to become the child process of the caller) is to create a new child process. When a new child process is created, both processes will execute the next instruction.

fork()Our return value can tell us when returning 0 that we are in the child process, if returning a positive value indicates that we are in the parent process, and if returning a negative value means that some error has occurred.

Example Code

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

Output Result

Parent process: 8023
Child process: 8024
$

The pseudo-terminal utility module pty is defined to handle the pseudo-terminal concept. With this feature, we can start another process or use a program to read from or write to the control terminal.

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 Result

The Process ID for the Current process is: 12508
The Process ID for the Child process is: 12509