Chandre Gowda
Chandre Gowda

Reputation: 930

Cannot kill a linux process using node js process.kill(pid)

Im trying to kill background running process using nodejs process.kill(pid, 'SIGTERM'), but the process is not getting killed.

I executed node script mentioned below and later checked the process using ps -efww | grep 19783 | grep -v grep from the prompt to confirm it is still not killed.

I can confirm that the process it is trying to kill is started by the same user, so there is no permission issue.

Is there something I need to pass to get the process killed.

Node Version: 8.11.1

OS: Linux 3.10.0-327.10.1.e17.x86_64

Reference : Node process

Code :

'use strict';

const argv = require('yargs').argv;
const exec = require('child_process').exec;

function execute(command) {
    console.log("Executing Command : ", command);
    return new Promise((resolve, reject) => {
        exec(command, {
            maxBuffer: 1024 * 5000000
        }, (error, stdout, stderr) => {
            if (error) {
                console.log(`ERROR: Something went wrong while executing ${command}: ${error}`);
                reject(error);
            } else {
                resolve(stdout);
            }
        });
    });
}

function kill(pid) {
    try {
        console.log(`Killing Process : ${pid}`);
        process.kill(pid, 'SIGTERM');
        let command = `ps -efww | grep ${pid} | grep -v grep | grep -v dzdo `;
        let output = execute(command).then(res => {
        console.log(`output: ${res}`);
        }).catch(err => console.log(err));
    } catch (e) {
        console.log(`Invalid Process ID:${pid}, failed during kill, "ERROR: ${e}"`);
    }
}

function main() {
    // remove all spaces;

    if (argv.kill) {
        let allPIDs = argv.kill || undefined;
        // console.log(`ALL PID's: ${allPIDs}`);
        allPIDs = allPIDs.toString().replace(/\s/, '').split(',');
        if (allPIDs.length > 0) {
            allPIDs.forEach(pid => {
                if (!isNaN(pid)) {
                    // console.log(`Valid PID: ${pid}`);
                    kill(pid);
                } else {
                    console.log(`ERROR: Invalid Process ID : ${pid}, Skipped Kill `);
                }
            });
        }
    }
}

main();

Assuming this code is saved as killer.js

Usage: node killer.js --kill=19783

Upvotes: 0

Views: 2131

Answers (1)

hackape
hackape

Reputation: 19957

Try SIGKILL instead of SIGTERM

The doc says

'SIGKILL' cannot have a listener installed, it will unconditionally terminate Node.js on all platforms.

So I think worth trying.

Upvotes: 2

Related Questions