如何删除已分配给端口的当前进程/应用程序?

例如:localhost:8080


当前回答

如果您已经知道端口号,那么向进程发送软件终止信号(SIGTERM)可能就足够了:

kill $(lsof -t -i :PORT_NUMBER)

其他回答

第一步(与KavinduWije所写的接受答案相同):

netstat -ano | findstr:yourPortNumber

第2步更改为:

tskill typeyourPIDhere 

注意:taskkill在某些git bash终端中不起作用

我为此写了一个很小的node js脚本。就像这样运行它: node killPort.js 8080或任何你需要杀死的端口。保存如下文件到killPort.js文件中:

const { exec } = require('child_process');
const fs = require(`fs`);

const port = process.argv.length > 2 ? process.argv[2] : ``;
if (!port || isNaN(port)) console.log(`port is required as an argument and has to be a number`);
else {
    exec(`netstat -ano | findstr :${port}`, (err, stdout, stderr) => {
        if (!stdout) console.log(`nobody listens on port ${port}`);
        else {
            const res = stdout.split(`\n`).map(s => s.trim());
            const pid = res.map(s => s.split(` `).pop()).filter(s => s).pop();
            console.log(`Listener of ${port} is found, its pid is ${pid}, killing it...`);
            exec(`taskkill /PID ${pid} /F`, (err, stdout, stderr) => {
                if (!stdout) console.log(`we tried to kill it, but not sure about the result, please run me again`);
                else console.log(stdout);
            })
        }
    });
}

对于Windows用户,您可以使用CurrPorts工具轻松地杀死正在使用的端口:

Windows 10/11默认工具:

第一步:

以管理员身份打开Windows PowerShell

第二步:

查找8080端口的PID (ProcessID):

netstat -aon | findstr 8080

TCP 0.0.0.0:8080 0.0.0.0:0 listen 77777

第三步:

杀死僵尸进程:

taskkill /f /pid 77777

“77777”是你的PID

我们可以通过简单地重新启动IIS来避免这种情况,使用下面的命令:

IISRESET