Open In App

Python | os.getpid() method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.getpid() method in Python is used to get the process ID of the current process.

os.getpid() method in Python is used to get the process ID of the current process.

os.getpid() Syntax in Python

Syntax: os.getpid()

Parameter: Not required

Return Type: This method returns an integer value denoting the process ID of the current process. The return type of this method is class ‘int

Python os.getpid() Method Example

Here, are various examples of find process using pid Python or os.getpid() method. So we are explaining some generally used examples of find process using pid Python method those are following.

Find Process using pid Python

In this example Python script imports the “os” module, retrieves the process ID of the current process using `os.getpid()`, and then prints the obtained process ID.

Python3
 # importing os module 
import os

# Get the process ID of
# the current process
pid = os.getpid()

# Print the process ID of
# the current process
print(pid) 

Output
2699


Get the Parent Process ID using os.getppid() Function

In this example Python code utilizes the os.getpid() method to retrieve the current process ID and os.getppid() to obtain the parent process ID. It then prints both the process ID and parent process ID.

Python3
import os

# Get the process ID of the current process
process_id = os.getpid()

# Get the parent process ID of the current process
parent_process_id = os.getppid()

# Print the process IDs
print("Process ID:", process_id)
print("Parent Process ID:", parent_process_id)

Output :

Process ID: <some_process_id>
Parent Process ID: <some_parent_process_id>

FAQ’s

1. How to determine pid of process started via os.system ?

To determine the PID of a process started via os.system, you can use subprocess module instead of os.system and then retrieve the PID from the subprocess object using subprocess.Popen.pid.

2. os.getpid returns PID that doesn’t exist?

os.getpid() typically returns the PID (Process ID) of the current running process. If you encounter a situation where os.getpid() seems to return a PID that doesn’t exist, it could be due to a delay between the time the process starts and when the PID is queried.


Last Updated : 14 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads