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() methodimport osimport signal# Get current process group idpgid = os.getpgid(os.getpid())if pgid == 1: # if parent process completedos.kill(os.getpid(), signal.SIGTERM)else: # otherwise stop group executionprint("Terminating whole program execution")os.killpg(os.getpgid(os.getpid()), signal.SIGCHLD)
Code explanation
- Lines 2 and 3: We import
osandsignalmodule in this program.
- Line 5: We invoke
os.getpgid()method to get the current process group ID. Theos.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. Theos.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.SIGTERMgenerates a termination signal for the current process. - Line 10: Otherwise, terminate the whole process group by invoking
os.killpg(). Here,signal.SIGCHLDterminates child process execution.