Node.js process.kill() Method
Last Updated :
17 Jan, 2022
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.
- ‘SIGTERM’ and ‘SIGINT‘ signals have default handlers on non-Windows platforms that reset the terminal mode before exiting with code 128 + signal number. If one of these signals has a listener installed, its default behavior on node.js will be removed.
- ‘SIGHUP’ is generated when the console window is closed.
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:
index.js
const displayInfo = () => {
console.log( 'Receiving SIGINT signal in nodeJS.' );
}
process.on( 'SIGINT' , displayInfo);
setTimeout(() => {
console.log( 'Exiting.' );
process.exit(0);
}, 100);
process.kill(process.pid, 'SIGINT' );
|
Command to run :
node index.js
Output :
Example 2 :
index.js
const displayInfo = () => {
console.log( 'Acknowledged SIGHUP signal in nodeJS.' );
}
process.on( 'SIGHUP' , displayInfo);
setTimeout(() => {
console.log( 'Exiting.' );
process.exit(0);
}, 100);
process.kill(process.pid, 'SIGHUP' );
|
Command to run :
node index.js
Output :
Reference : https://nodejs.org/api/process.html#process_process_kill_pid_signal
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...