getpid in Python

The os module of Python provides the getpid() method which returns the process id of the current process.The python examples calls getpid() in a normal scenario as well under a forked scenario.

Os Updated 14 Nov 2018 1 min read

Method Name

os.getpid

Method Signature

os.getpid()

Parameters

None

Method Overview

  • In any modern operating system, every process will have an id usually an integer that is assigned to an active process.

  • The method getpid() of the Python os module, returns the current process Id.

  • Process Id or pid is consumed by several methods like os.kill(), os.getsid() and so on.

  • The following screenshot lists all the processes running under the operating system ( the list that can be shown to the current user) along with the process Ids as given by the command ps -A.os.getpid() method in Python

Example 1

python
import os

print("PID of the current process is:")

print(os.getpid())

Output

Output
PID of the current process is:

2842

Example 2

python
import os

retVal  = os.fork()

pid     = os.getpid()

if retVal is 0:

    print("PID of the child process is: %d"%(pid))

else:

    pid     = os.getpid()

    print("PID of the parent process is: %d"%(pid))

Output

Output
PID of the parent process is: 2850

PID of the child process is: 2851