Open In App

Node.js process.kill() Method

The process.kill( pid[,signal] ) is an inbuilt method of node.js which sends a signal to the process, pid (which is the process id) and signal is in the string format that is the signal to send.

Syntax :



process.kill(pid[, signal])

Parameters: This method accepts two parameters as mentioned above and described below:

Note : If no signal specified, then by default ‘SIGTERM’ will be the signal.

Return value : The process.kill() method will throw an error if the target pid is not found or doesn’t exist. This method returns boolean value 0 if pid exists and can be used as a test for the existence of the target process. For window users, this method will also throw an error if pid is used to kill a group of process. 

Below examples illustrate the use of process.kill() property in Node.js:

Example 1:




// Node.js program to demonstrate the 
// process.kill(pid[, signal]) method 
  
  
// Printing process signal acknowledged
const displayInfo = () => {
  console.log('Receiving SIGINT signal in nodeJS.');
}
  
// Initiating a process
process.on('SIGINT', displayInfo);
  
setTimeout(() => {
  console.log('Exiting.');
  process.exit(0);
}, 100);
  
// kill the process with pid and signal = 'SIGINT'     
process.kill(process.pid, 'SIGINT');

Command to run :

node index.js

Output :

Example 2 :




// Node.js program to demonstrate the 
// process.kill(pid[, signal]) method 
// Printing process signal acknowledged
const displayInfo = () => {
  console.log('Acknowledged SIGHUP signal in nodeJS.');
}
  
// Initiating a process
process.on('SIGHUP', displayInfo);
  
setTimeout(() => {
  console.log('Exiting.');
  process.exit(0);
}, 100);
  
// kill the process with pid and signal = 'SIGHUP'     
process.kill(process.pid, 'SIGHUP');

Command to run :

node index.js

Output :

Reference : https://nodejs.org/api/process.html#process_process_kill_pid_signal


Article Tags :