What is os.killpg() method in Python?

Overview

The os.killpg() method signals the process group.

Note: os.killpg() is only available for UNIX based systems.

Syntax


os.killpg(pgid, sig)

Parameters

It takes the following argument values:

  • pgid: The current process group id.
  • sig: The signal type to the processor.

Return value

It does not return any value.

Code example

In this code snippet, we'll discuss os.killpg() of Python OS module. The os.killpg() will help to stop the execution of the current process group.

# Program to check os.killpg() method
import os
import signal
# Get current process group id
pgid = os.getpgid(os.getpid())
if pgid == 1: # if parent process completed
os.kill(os.getpid(), signal.SIGTERM)
else: # otherwise stop group execution
print("Terminating whole program execution")
os.killpg(os.getpgid(os.getpid()), signal.SIGCHLD)

Code explanation

  • Lines 2 and 3: We import os and signal module in this program.
  • Line 5: We invoke os.getpgid() method to get the current process group ID. The os.getpgid() takes the current process id as an argument. For this, we use os.getpid().
  • Line 7: If sub-processes of this current process are already completed, we invoke os.kill() to stop. The os.kill() takes two argument values:
    • Process ID: It is the process's unique identifier.
    • Signal: It is an additional signal to the Python virtual machine to stop execution. Here signal.SIGTERM generates a termination signal for the current process.
  • Line 10: Otherwise, terminate the whole process group by invoking os.killpg(). Here, signal.SIGCHLD terminates child process execution.

Free Resources