Python
  • Getting Started
    • Input and Output
    • Variables
    • Data Types
    • Conditional Structures
      • Humidity Level
      • Financial Transactions
      • Fruit-Vending Machine
      • Magic While
      • FizzBuzz
    • Functions
      • Hashtag Generator
  • Data Structures
    • Lists
    • Dictionary
    • Set
    • Interpreter Expressions
  • OOPs
    • Classes and Objects
    • Exception Handling
      • Simple Calculator
  • System Programming
    • File Operations
    • Directory Navigation
    • Process Creation
    • Threads
Powered by GitBook
On this page
  1. System Programming

Process Creation

I LOVE DOING THIS :)

Whenever, we execute our python program - it becomes a process and sits in the pstable (process table) in the backend, Irrespective of the operating system

So in this exercise we are going to create a process, within the process (our .py program)

Forking ?

  • Cloning of an existing process

  • Forking creates an identical process as the parent process

  • The execution is duplicated exactly at the point of call to the fork()

returns 0 in the child process

returns pid (process id) in the parent process

  • Pid is different for the parent and child process

To explain these confusing topics, I've written a simple program below

#!/opt/python3

import os

def child():
	print("Hi I'm the newly born child process with the forked PID %d" % os.getpid())

def parent():
	print("Hi im the parent process and my PID is %d" % os.getpid())
	
	fork_the_child = os.fork()
	
	if fork_the_child == 0 :
		
		# Inside the child process
		child()
	else:
		
		# Inside the parent process 
		print("Forked a child now and my PID is %d" % fork_the_child)

parent()
  • We are defining a child process first with a print statement returning it's PID using os.getpid()

  • And then we are defining the parent process which forks the child using os.fork() method

  • If the fork_the_child variable is equal to zero (Basically, it must be as at the time of fork call the child's process is 0) then it executes the child process

  • Else, it executes the print statement with the forked child's PID

To represent it in the simplest way would be

import os

def parent():

	fork_the_child = os.fork()

	if fork_the_child == 0:
		print("Im the child with pid %d" % fork_the_child)
	else:
		print("Im the parent with pid %d" % os.getpid())

parent()
PreviousDirectory NavigationNextThreads

Last updated 2 years ago