Python | os.kill() method
os.kill() method in Python is used to send a specified signal to the process with a specified process ID. Constants for the specific signals available on the host platform are defined in the Signal Module.
os.kill() Method Syntax in Python
Syntax: os.kill(pid, sig)
Parameters:
- pid: An integer value representing process id to which signal is to be sent.
- sig An integer representing signal number or the signal constant available on the host platform defined in the signal module to be sent.
Return type: This method does not return any value.
Python os.kill() Function Examples
Sending a SIGTERM
Signal to a Process
In this example, the script creates a child process using os.fork()
and retrieves its process ID. It then attempts to send a SIGTERM
signal to the child process using os.kill()
, providing feedback based on the success or failure of the signal transmission.
Python3
import os import signal # Define the process ID of the target process pid = os.fork() # Send a SIGTERM signal to the process try : os.kill(pid, signal.SIGTERM) print (f "Sent SIGTERM signal to process {pid}" ) except OSError: print (f "Failed to send SIGTERM signal to process {pid}" ) |
Sent SIGTERM signal to process 22
Python Kill Process Using os.kill() Method
In this example, the script creates a child process using os.fork()
. The parent process sends a SIGSTOP
signal to the child, causing it to pause execution. It then retrieves information about the child process’s status using os.waitpid()
and displays the signal that caused the child to stop.
Python3
import os import signal pid = os.fork() if pid: print ( "In parent process" ) os.kill(pid, signal.SIGSTOP) print ( "Signal sent, child stopped." ) info = os.waitpid(pid, os.WSTOPPED) stopSignal = os.WSTOPSIG(info[ 1 ]) print ( "Child stopped due to signal no:" , stopSignal) print ( "Signal name:" , signal.Signals(stopSignal).name) # send signal 'SIGCONT' os.kill(pid, signal.SIGCONT) print ( "\nSignal sent, child continued." ) else : print ( "\nIn child process" ) print ( "Process ID:" , os.getpid()) print ( "Hello ! Beginner" ) print ( "Exiting" ) |
In parent process Signal sent, child stopped. Child stopped due to signal no: 19 Signal name: SIGSTOP Signal sent, child continued. In child process Process ID: 21 Hello ! Beginner Exiting
Contact Us