我正在尝试使用nodejs process.kill(pid, 'SIGTERM')
杀死后台运行的进程,但是该进程没有被杀死。
我执行了下面提到的节点脚本,然后在提示符下使用ps -efww | grep 19783 | grep -v grep
检查了该进程,以确认它仍然未被杀死。
我可以确认它试图杀死的进程是由同一用户启动的,因此没有权限问题。
我需要传递一些东西来杀死进程。
节点版本: 8.11.1
操作系统: Linux 3.10.0-327.10.1.e17.x86_64
参考:Node process
代码:
'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();
假定此代码另存为killer.js
用法:node killer.js --kill=19783