gpt4 book ai didi

javascript - 无法使用 Node js process.kill(pid) 终止 linux 进程

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:40 25 4
gpt4 key购买 nike

我试图使用 nodejs process.kill(pid, 'SIGTERM') 终止后台运行的进程,但进程没有被终止。

我执行了下面提到的 Node 脚本,后来使用 ps -efww | 检查了进程grep 19783 | grep -v grep 从提示中确认它仍然没有被杀死。

我可以确认它试图终止的进程由同一用户启动,因此不存在权限问题。

是否需要传递一些信息才能终止进程。

Node 版本: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

最佳答案

尝试使用 SIGKILL 而不是 SIGTERM

doc

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

所以我觉得值得一试。

关于javascript - 无法使用 Node js process.kill(pid) 终止 linux 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55682963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com