Python os.kill() Method

Python os.kill() Method

  1. Syntax of the os.kill() Method
  2. Example Codes: Working With the os.kill() Method in Python
  3. Example Codes: Understanding the os.kill() Method in Python

Python os.kill() method is an efficient way of killing or terminating a process using its process identifier (pid).

Syntax of the os.kill() Method

os.kill(pid, signal)

Parameters

pid It is an integer representing an ID of the process we are addressing.
signal It is an integer representing a signal number needed to send to the process.

Return

In the execution process, this method does not return any value.

Example Codes: Working With the os.kill() Method in Python

import os, signal

pID = os.fork()

if pID :
    print("---PARENT PROCESS---")

    os.kill(pID, signal.SIGSTOP)

    print("The parent process has been killed.")

    os.kill(pID, signal.SIGCONT)

else :

    print("Hello, World!")

Output:

---PARENT PROCESS---
The parent process has been killed.
Hello, World!

Python offers different signal modules. In the above code, variables signal.SIGSTOP are used to stop the current process.

Another variable, signal.SIGCONT, is used, which continues the current process.

Example Codes: Understanding the os.kill() Method in Python

import os

import signal

def process():
    print ("The process ID:", os.getpid())

    os.kill(os.getpid(), signal.SIGKILL)

process()

Output:

The process ID: 6362

Every time we run the above code, a new process executes; thus, different process IDs are obtained. In the above code, the variable signal.SIGKILL is used to kill the current process.

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python OS

  • Python os.set_handle_inheritable() Method
  • Python os.set_inheritable() Method
  • Python os.stat_result Class
  • Python os.renames() Method
  • Python os.get_handle_inheritable Method
  • Python os.get_inheritable Method