├── .editorconfig ├── .gitattributes ├── .github └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── cli.js ├── fixture.js ├── interactive.js ├── license ├── package.json ├── readme.md ├── screenshot.svg └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} on ${{ matrix.os }} 8 | runs-on: ${{ matrix.os }} 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 20 14 | - 18 15 | os: 16 | - ubuntu-latest 17 | - macos-latest 18 | - windows-latest 19 | steps: 20 | - uses: actions/checkout@v4 21 | - uses: actions/setup-node@v4 22 | with: 23 | node-version: ${{ matrix.node-version }} 24 | - run: npm install 25 | - run: npm test 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /cli.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import process from 'node:process'; 3 | import meow from 'meow'; 4 | import fkill from 'fkill'; 5 | 6 | const cli = meow(` 7 | Usage 8 | $ fkill [ …] 9 | 10 | Options 11 | --force -f Force kill 12 | --verbose -v Show process arguments 13 | --silent -s Silently kill and always exit with code 0 14 | --force-after-timeout , -t Force kill processes which didn't exit after N seconds 15 | 16 | Examples 17 | $ fkill 1337 18 | $ fkill safari 19 | $ fkill :8080 20 | $ fkill 1337 safari :8080 21 | $ fkill 22 | 23 | To kill a port, prefix it with a colon. For example: :8080. 24 | 25 | Run without arguments to use the interactive mode. 26 | In interactive mode, 🚦n% indicates high CPU usage and 🐏n% indicates high memory usage. 27 | Supports fuzzy search in the interactive mode. 28 | 29 | The process name is case insensitive. 30 | `, { 31 | importMeta: import.meta, 32 | inferType: true, 33 | flags: { 34 | force: { 35 | type: 'boolean', 36 | shortFlag: 'f', 37 | }, 38 | verbose: { 39 | type: 'boolean', 40 | shortFlag: 'v', 41 | }, 42 | silent: { 43 | type: 'boolean', 44 | shortFlag: 's', 45 | }, 46 | forceAfterTimeout: { 47 | type: 'number', 48 | shortFlag: 't', 49 | }, 50 | }, 51 | }); 52 | 53 | if (cli.input.length === 0) { 54 | const interactiveInterface = await import('./interactive.js'); 55 | interactiveInterface.init(cli.flags); 56 | } else { 57 | const forceAfterTimeout = cli.flags.forceAfterTimeout === undefined ? undefined : cli.flags.forceAfterTimeout * 1000; 58 | const promise = fkill(cli.input, {...cli.flags, forceAfterTimeout, ignoreCase: true}); 59 | 60 | if (!cli.flags.force) { 61 | try { 62 | await promise; 63 | } catch (error) { 64 | if (!cli.flags.silent) { 65 | if (error.message.includes('Could not find a process with port')) { 66 | console.error(error.message); 67 | process.exit(1); 68 | } 69 | 70 | const interactiveInterface = await import('./interactive.js'); 71 | interactiveInterface.handleFkillError(cli.input); 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /fixture.js: -------------------------------------------------------------------------------- 1 | import process from 'node:process'; 2 | import http from 'node:http'; 3 | 4 | const server = http.createServer((request, response) => { 5 | response.end(); 6 | }); 7 | 8 | server.listen(process.argv.slice(2)[0]); 9 | -------------------------------------------------------------------------------- /interactive.js: -------------------------------------------------------------------------------- 1 | import process from 'node:process'; 2 | import chalk from 'chalk'; 3 | import inquirer from 'inquirer'; 4 | import inquirerAutocompletePrompt from 'inquirer-autocomplete-prompt'; 5 | import psList from 'ps-list'; 6 | import {numberSortDescending} from 'num-sort'; 7 | import escExit from 'esc-exit'; 8 | import cliTruncate from 'cli-truncate'; 9 | import {allPortsWithPid} from 'pid-port'; 10 | import fkill from 'fkill'; 11 | import {processExists} from 'process-exists'; 12 | import FuzzySearch from 'fuzzy-search'; 13 | 14 | const isWindows = process.platform === 'win32'; 15 | const commandLineMargins = 4; 16 | 17 | const PROCESS_EXITED_MIN_INTERVAL = 5; 18 | const PROCESS_EXITED_MAX_INTERVAL = 1280; 19 | 20 | const delay = ms => new Promise(resolve => { 21 | setTimeout(resolve, ms); 22 | }); 23 | 24 | const processExited = async (pid, timeout) => { 25 | const endTime = Date.now() + timeout; 26 | let interval = PROCESS_EXITED_MIN_INTERVAL; 27 | if (interval > timeout) { 28 | interval = timeout; 29 | } 30 | 31 | let exists; 32 | 33 | do { 34 | await delay(interval); // eslint-disable-line no-await-in-loop 35 | 36 | exists = await processExists(pid); // eslint-disable-line no-await-in-loop 37 | 38 | interval *= 2; 39 | if (interval > PROCESS_EXITED_MAX_INTERVAL) { 40 | interval = PROCESS_EXITED_MAX_INTERVAL; 41 | } 42 | } while (Date.now() < endTime && exists); 43 | 44 | return !exists; 45 | }; 46 | 47 | const preferNotMatching = matches => (a, b) => { 48 | const aMatches = matches(a); 49 | return matches(b) === aMatches ? 0 : (aMatches ? 1 : -1); 50 | }; 51 | 52 | const deprioritizedProcesses = new Set(['iTerm', 'iTerm2', 'fkill']); 53 | const isDeprioritizedProcess = process_ => deprioritizedProcesses.has(process_.name); 54 | const preferNotDeprioritized = preferNotMatching(isDeprioritizedProcess); 55 | const preferLowAlphanumericNames = (a, b) => a.name.localeCompare(b.name); 56 | 57 | const preferHighPerformanceImpact = (a, b) => { 58 | const hasCpu = typeof a.cpu === 'number' && typeof b.cpu === 'number'; 59 | const hasMemory = typeof a.memory === 'number' && typeof b.memory === 'number'; 60 | 61 | if (hasCpu && hasMemory) { 62 | return numberSortDescending(a.cpu + a.memory, b.cpu + b.memory); 63 | } 64 | 65 | if (hasCpu) { 66 | return numberSortDescending(a.cpu, b.cpu); 67 | } 68 | 69 | if (hasMemory) { 70 | return numberSortDescending(a.memory, b.memory); 71 | } 72 | 73 | return 0; 74 | }; 75 | 76 | const preferHeurisicallyInterestingProcesses = (a, b) => { 77 | let result; 78 | 79 | result = preferNotDeprioritized(a, b); 80 | if (result !== 0) { 81 | return result; 82 | } 83 | 84 | result = preferHighPerformanceImpact(a, b); 85 | if (result !== 0) { 86 | return result; 87 | } 88 | 89 | return preferLowAlphanumericNames(a, b); 90 | }; 91 | 92 | const filterProcesses = (input, processes, flags) => { 93 | const memoryThreshold = flags.verbose ? 0 : 1; 94 | const cpuThreshold = flags.verbose ? 0 : 3; 95 | 96 | const filteredProcesses = new FuzzySearch( 97 | processes, 98 | [ 99 | // The name is truncated for some reason, so we always use `cmd` for now. 100 | 'cmd', 101 | /// flags.verbose && !isWindows ? 'cmd' : 'name', 102 | 'pid', 103 | ], 104 | { 105 | caseSensitive: false, 106 | }, 107 | ) 108 | .search(input); 109 | 110 | return filteredProcesses 111 | .filter(process_ => !( 112 | process_.name.endsWith('-helper') 113 | || process_.name.endsWith('Helper') 114 | || process_.name.endsWith('HelperApp') 115 | )) 116 | .sort(preferHeurisicallyInterestingProcesses) 117 | .map(process_ => { 118 | const renderPercentage = percents => { 119 | const digits = Math.floor(percents * 10).toString().padStart(2, '0'); 120 | const whole = digits.slice(0, -1); 121 | const fraction = digits.slice(-1); 122 | return fraction === '0' ? `${whole}%` : `${whole}.${fraction}%`; 123 | }; 124 | 125 | const lineLength = process.stdout.columns || 80; 126 | const ports = process_.ports.length === 0 ? '' : (' ' + process_.ports.slice(0, 4).map(x => `:${x}`).join(' ')); 127 | const memory = (process_.memory !== undefined && (process_.memory > memoryThreshold)) ? ` 🐏${renderPercentage(process_.memory)}` : ''; 128 | const cpu = (process_.cpu !== undefined && (process_.cpu > cpuThreshold)) ? `🚦${renderPercentage(process_.cpu)}` : ''; 129 | const margins = commandLineMargins + process_.pid.toString().length + ports.length + memory.length + cpu.length; 130 | const length = lineLength - margins; 131 | const name = cliTruncate(flags.verbose && !isWindows ? process_.cmd : process_.name, length, {position: 'middle', preferTruncationOnSpace: true}); 132 | const extraMargin = 2; 133 | const spacer = lineLength === process.stdout.columns ? ''.padEnd(length - name.length - extraMargin) : ''; 134 | 135 | return { 136 | name: `${name} ${chalk.dim(process_.pid)}${spacer}${chalk.dim(ports)}${cpu}${memory}`, 137 | value: process_.pid, 138 | }; 139 | }); 140 | }; 141 | 142 | const handleFkillError = async processes => { 143 | const suffix = processes.length > 1 ? 'es' : ''; 144 | 145 | if (process.stdout.isTTY === false) { 146 | console.error(`Error killing process${suffix}. Try \`fkill --force ${processes.join(' ')}\``); 147 | process.exit(1); // eslint-disable-line unicorn/no-process-exit 148 | } else { 149 | const answer = await inquirer.prompt([{ 150 | type: 'confirm', 151 | name: 'forceKill', 152 | message: 'Error killing process. Would you like to use the force?', 153 | }]); 154 | 155 | if (answer.forceKill === true) { 156 | await fkill(processes, { 157 | force: true, 158 | ignoreCase: true, 159 | }); 160 | } 161 | } 162 | }; 163 | 164 | const DEFAULT_EXIT_TIMEOUT = 3000; 165 | 166 | const performKillSequence = async processes => { 167 | if (!Array.isArray(processes)) { 168 | processes = [processes]; 169 | } 170 | 171 | let didSurvive; 172 | let hadError; 173 | try { 174 | await fkill(processes); 175 | const exited = await Promise.all(processes.map(process => processExited(process, DEFAULT_EXIT_TIMEOUT))); 176 | didSurvive = processes.filter((_, i) => !exited[i]); 177 | } catch (error) { 178 | didSurvive = processes; 179 | hadError = error; 180 | } 181 | 182 | if (didSurvive.length === 0) { 183 | return; 184 | } 185 | 186 | const suffix = didSurvive.length > 1 ? 'es' : ''; 187 | const problemText = hadError ? `Error killing process${suffix}.` : `Process${suffix} didn't exit in ${DEFAULT_EXIT_TIMEOUT}ms.`; 188 | 189 | if (process.stdout.isTTY === false) { 190 | console.error(`${problemText} Try \`fkill --force ${didSurvive.join(' ')}\``); 191 | process.exit(1); // eslint-disable-line unicorn/no-process-exit 192 | } 193 | 194 | const answer = await inquirer.prompt([{ 195 | type: 'confirm', 196 | name: 'forceKill', 197 | message: `${problemText} Would you like to use the force?`, 198 | }]); 199 | 200 | if (!answer.forceKill) { 201 | return; 202 | } 203 | 204 | await fkill(processes, { 205 | force: true, 206 | ignoreCase: true, 207 | }); 208 | }; 209 | 210 | const listProcesses = async (processes, flags) => { 211 | inquirer.registerPrompt('autocomplete', inquirerAutocompletePrompt); 212 | 213 | const answer = await inquirer.prompt([{ 214 | name: 'processes', 215 | message: 'Running processes:', 216 | type: 'autocomplete', 217 | pageSize: 10, 218 | source: async (answers, input) => filterProcesses(input, processes, flags), 219 | }]); 220 | 221 | performKillSequence(answer.processes); 222 | }; 223 | 224 | const init = async flags => { 225 | escExit(); 226 | 227 | const getPortsFromPid = (value, list) => { 228 | const ports = []; 229 | 230 | for (const [key, listValue] of list.entries()) { 231 | if (value === listValue) { 232 | ports.push(String(key)); 233 | } 234 | } 235 | 236 | return ports; 237 | }; 238 | 239 | const [pids, processes] = await Promise.all([ 240 | allPortsWithPid(), 241 | psList({all: false}), 242 | ]); 243 | 244 | const procs = processes.map(process_ => ({...process_, ports: getPortsFromPid(process_.pid, pids)})); 245 | listProcesses(procs, flags); 246 | }; 247 | 248 | export {init, handleFkillError}; 249 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fkill-cli", 3 | "version": "8.0.0", 4 | "description": "Fabulously kill processes. Cross-platform.", 5 | "license": "MIT", 6 | "repository": "sindresorhus/fkill-cli", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "bin": { 15 | "fkill": "./cli.js" 16 | }, 17 | "sideEffects": false, 18 | "engines": { 19 | "node": ">=18" 20 | }, 21 | "scripts": { 22 | "test": "xo && ava" 23 | }, 24 | "files": [ 25 | "cli.js", 26 | "interactive.js" 27 | ], 28 | "keywords": [ 29 | "cli-app", 30 | "cli", 31 | "fkill", 32 | "kill", 33 | "killing", 34 | "killall", 35 | "taskkill", 36 | "sigkill", 37 | "sigterm", 38 | "force", 39 | "exit", 40 | "zap", 41 | "die", 42 | "ps", 43 | "proc" 44 | ], 45 | "dependencies": { 46 | "chalk": "^5.3.0", 47 | "cli-truncate": "^4.0.0", 48 | "esc-exit": "^3.0.0", 49 | "fkill": "^9.0.0", 50 | "fuzzy-search": "^3.2.1", 51 | "inquirer": "^9.2.11", 52 | "inquirer-autocomplete-prompt": "^3.0.1", 53 | "meow": "^12.1.1", 54 | "num-sort": "^3.0.0", 55 | "pid-port": "^1.0.0", 56 | "ps-list": "^8.1.1" 57 | }, 58 | "devDependencies": { 59 | "ava": "^5.3.1", 60 | "delay": "^6.0.0", 61 | "execa": "^8.0.1", 62 | "get-port": "^7.0.0", 63 | "noop-process": "^5.0.0", 64 | "process-exists": "^5.0.0", 65 | "xo": "^0.56.0" 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 |

2 |
3 | fkill 4 |
5 |
6 |
7 |

8 | 9 | > Fabulously kill processes. Cross-platform. 10 | 11 | Works on macOS, Linux, and Windows. 12 | 13 | ## Install 14 | 15 | ```sh 16 | npm install --global fkill-cli 17 | ``` 18 | 19 | ## Usage 20 | 21 | ``` 22 | $ fkill --help 23 | 24 | Usage 25 | $ fkill [ …] 26 | 27 | Options 28 | --force, -f Force kill 29 | --verbose, -v Show process arguments 30 | --silent, -s Silently kill and always exit with code 0 31 | --force-timeout , -t Force kill processes which didn't exit after N seconds 32 | 33 | Examples 34 | $ fkill 1337 35 | $ fkill safari 36 | $ fkill :8080 37 | $ fkill 1337 safari :8080 38 | $ fkill 39 | 40 | To kill a port, prefix it with a colon. For example: :8080. 41 | 42 | Run without arguments to use the interactive interface. 43 | In interactive mode, 🚦n% indicates high CPU usage and 🐏n% indicates high memory usage. 44 | Supports fuzzy search in the interactive mode. 45 | 46 | The process name is case insensitive. 47 | ``` 48 | 49 | ## Interactive UI 50 | 51 | Run `fkill` without arguments to launch the interactive UI. 52 | 53 | ![](screenshot.svg) 54 | 55 | ## Related 56 | 57 | - [fkill](https://github.com/sindresorhus/fkill) - API for this module 58 | - [alfred-fkill](https://github.com/SamVerschueren/alfred-fkill) - Alfred workflow for this module 59 | -------------------------------------------------------------------------------- /screenshot.svg: -------------------------------------------------------------------------------- 1 | ~fkill?Runningprocesses:(Usearrowkeysortypetosearch)systemd444(sd-pam)446startx452xinit479Xorg480openbox487dbus-daemon490polkit-gnome-au508ksuperkey518ksuperkey519(Moveupanddowntorevealmorechoices)?Runningprocesses:cSearching...compton528xfconfd532conky601xfce4-power-man623gvfs-afc-volume1575dconf-service1664code-insiders1771code-insiders1773code-insiders1807code-insiders1878?Runningprocesses:chchrome3137chrome3755chrome3807chrome3847chrome3877chrome26063:45837:5353chrome-sandbox26071chrome26072chrome-sandbox26074chrome26077?Runningprocesses:chr?Runningprocesses:chro?Runningprocesses:chrom?Runningprocesses:chromechrome3137chrome3755chrome3807chrome3847chrome3877chrome26063:45837:5353?Runningprocesses:chrome26063:45837:5353~6sffkfkifkil -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import childProcess from 'node:child_process'; 2 | import test from 'ava'; 3 | import {execa} from 'execa'; 4 | import delay from 'delay'; 5 | import noopProcess from 'noop-process'; 6 | import {processExists} from 'process-exists'; 7 | import getPort from 'get-port'; 8 | 9 | const noopProcessKilled = async (t, pid) => { 10 | // Ensure the noop process has time to exit 11 | await delay(100); 12 | t.false(await processExists(pid)); 13 | }; 14 | 15 | test('main', async t => { 16 | const {stdout} = await execa('./cli.js', ['--version']); 17 | t.true(stdout.length > 0); 18 | }); 19 | 20 | test('pid', async t => { 21 | const pid = await noopProcess(); 22 | await execa('./cli.js', ['--force', pid]); 23 | await noopProcessKilled(t, pid); 24 | }); 25 | 26 | // TODO: Upgrading AVA to latest caused this to not finish. Unclear why. 27 | // test('fuzzy search', async t => { 28 | // const pid = await noopProcess({title: '!noo00oop@'}); 29 | // await execa('./cli.js', ['o00oop@']); 30 | // await noopProcessKilled(t, pid); 31 | // }); 32 | 33 | test('kill from port', async t => { 34 | const port = await getPort(); 35 | const {pid} = childProcess.spawn('node', ['fixture.js', port]); 36 | await execa('./cli.js', ['--force', pid]); 37 | await noopProcessKilled(t, pid); 38 | }); 39 | 40 | test('error when process is not found', async t => { 41 | await t.throwsAsync( 42 | execa('./cli.js', ['--force', 'notFoundProcess']), 43 | {message: /Killing process notFoundProcess failed: Process doesn't exist/}, 44 | ); 45 | }); 46 | 47 | test('force killing process at unused port throws error', async t => { 48 | await t.throwsAsync( 49 | execa('./cli.js', ['--force', ':1337']), 50 | {message: /Killing process :1337 failed: Process doesn't exist/}, 51 | ); 52 | }); 53 | 54 | test('silently force killing process at unused port exits with code 0', async t => { 55 | const {exitCode} = await execa('./cli.js', ['--force', '--silent', ':1337']); 56 | t.is(exitCode, 0); 57 | }); 58 | --------------------------------------------------------------------------------