Getppid In Python Os Module

Method Name:

os.getppid

 

Method Signature:

os.getppid()

 

Parameters:

None

 

Method Overview:

  • The getppid() method of the Python os module returns the pid i.e.,the process id, of the parent process.
  • A parent process is a process, which has created a child process.

Example 1:

import os

 

print("Parent process Id of this running Python program:")

print(os.getppid())

 

Output:

Parent process Id of this running Python program:

1118

 

Running the below commands from the terminal corroborates the above output

$echo $$

$1118

 

$ps -p 1118 -o comm

$COMM

-bash

 

Both the outputs above confirm the process id 1118 is the pid of the –bash shell which ran the python program.

 

Example 2:

import os

 

# Print the parent of this program's process

print("Parent process Id of this running Python program:")

shell = os.getppid()

print(os.getppid())

 

print("From child process:My process id is:%d"%(os.getpid()))

 

 

# Create a child process

retVal = os.fork()

 

if retVal is 0:

    print("From grandchild process:")

    print("From grandchild process:My process id is:%d"%(os.getpid()))

    print("From grandchild process:Parent id of this child is/was:%d"%(os.getppid()))

    print("From grandchild process:My grandparent is/was %d:"%(shell))   

    print("Child process exiting")   

      

else:

    for index in range(1, 10):

        print("Parent process printing value:%d"%(index))   

    print("Parent process exiting")

 

Output:

Parent process Id of this running Python program:

1118

From child process:My process id is:3420

Parent process printing value:1

Parent process printing value:2

Parent process printing value:3

Parent process printing value:4

Parent process printing value:5

Parent process printing value:6

Parent process printing value:7

Parent process printing value:8

Parent process printing value:9

Parent process exiting

From grand child process:

From grand child process:My process id is:3421

From grand child process:Parent id of this child is/was:3420

From grand child process:My grand parent is/was 1118:

Child process exiting


Copyright 2023 © pythontic.com