serialkiller
Version:
SerialKiller is a process killer tool for Unix/Linux environments.
111 lines (93 loc) • 3.13 kB
JavaScript
const exec = require('child_process').exec;
const chalk = require('chalk');
const meow = require('meow');
const cLog = console.log;
const cError = console.error;
const cli = meow(
`
Usage
$serialkiller < option > <processname>
or
serialkiller <processname>
options for the serialkiller are same as options for kill Commands
1 HUP (hang up)
2 INT (interrupt)
3 QUIT (quit)
6 ABRT (abort)
9 KILL (non-catchable, non-ignorable kill)
14 ALRM (alarm clock)
15 TERM (software termination signal)
Example:
serialkiller 9 tomcat
or
serialkiller KILL tomcat
or
serialkiller tomcat`
);
const validateOption = (options) => {
const killOptions1 = ['1', '2', '3', '6', '9', '14', '15'];
const killOptions2 = ['HUP', 'INT', 'QUIT', 'ABRT', 'KILL', 'ALRM', 'TERM'];
const killOperands = ['l', 's', 'signal_name', 'signal_number'];
if (
(options.length < 2 &&
(killOptions1.find((x) => x === options[0]) || killOptions2.find((x) => x === options[0]))) ||
(options.length < 3 &&
(killOptions1.find((x) => x === options[1]) || killOptions2.find((x) => x === options[1])) &&
killOperands.find((x) => x === options[0]))
) {
return true;
} else {
return false;
}
};
const search = async (value, options = []) => {
exec(`ps -ef | grep ${value} | awk '{ print $2 }'`, (error, stdout, stderr) => {
if (error) {
cError(chalk.blue('exec error:') + chalk.red(error));
return;
}
if (stdout) {
if (options.length === 0) {
killProcess(stdout, options);
} else {
if (validateOption(options)) {
options.map((x) => `-${x}`) && killProcess(stdout, options);
} else {
cLog('Inappropriate options are selected, please enter try `serialkiller --help`');
}
}
}
stderr && cLog(chalk.blue('stderr: \n') + chalk.red(stderr));
});
};
const killProcess = async (processIds = [], options = []) => {
options = options.map((x) => (x = `-${x}`));
processIds.split('\n').forEach(
(x) =>
x !== '' &&
exec(`ps -p ${x}`, (error, stdout, stderr) => {
!error &&
exec(`kill ${options} ${x}`, (error, stdout, stderr) => {
if (error) {
cError(chalk.blue('exec error:') + chalk.red(error));
return;
}
stdout && cLog(chalk.yellow('stdout: \n') + chalk.green(stdout));
stderr && cLog(chalk.blue('stderr: \n') + chalk.red(stderr));
});
})
);
};
module.exports = serialkiller = (userArgs) => {
if (userArgs.length > 0 && userArgs.length < 4) {
if (userArgs.length === 1) {
search(userArgs[userArgs.length - 1]);
} else {
search(userArgs[userArgs.length - 1], userArgs.splice(0, userArgs.length - 1));
}
} else {
cLog('Inappropriate options are selected, please enter try `serialkiller --help`');
}
};
serialkiller(cli.input);