AgentSkillsCN

safe-port-kill

通过精准定位仅监听状态的进程(即服务器端),安全地终止指定 TCP 端口,而绝不影响已建立连接的客户端。当用户提出“关闭某个端口”“释放端口”“停止端口 X 上运行的程序”等需求时,或在编写相关代码与脚本时,均可运用此技能。

SKILL.md
--- frontmatter
name: safe-port-kill
description: Kill a TCP port safely by targeting only the LISTEN process (the server) and never killing connected clients. This skill should be used when asked to "kill a port", "free port", "stop what's running on port X", or when writing code/scripts to do so.

Safe Port Kill

[Created by Codex: 019bf112-2df0-7130-bbe8-9e0936799a45 2026-01-24]

Overview

Kill the process that is LISTENing on a TCP port (the server) while avoiding collateral damage to connected client processes that merely have established connections to that port.

Non-Negotiable Rule

When selecting PIDs “on a port”, filter to LISTEN sockets only.

Reason: commands like lsof -tiTCP:<port> return both the server PID and client PIDs with ESTABLISHED connections to the server. Killing those PIDs kills your browser/Electron clients, not just the service.

macOS (lsof) Cheat Sheet

Inspect everything touching the port (server + clients):

bash
lsof -nP -iTCP:<PORT>

Get only the server PID(s) (LISTEN-only):

bash
lsof -tiTCP:<PORT> -sTCP:LISTEN

Kill only the server PID(s) (graceful → force):

bash
lsof -tiTCP:<PORT> -sTCP:LISTEN | xargs -n1 kill
sleep 0.5
lsof -tiTCP:<PORT> -sTCP:LISTEN | xargs -n1 kill -9

In Code (Recommended Pattern)

Implement PID selection as “LISTEN-only”.

Minimal Python approach:

python
import subprocess

def listener_pids(port: int) -> list[int]:
    out = subprocess.run(
        ["lsof", f"-tiTCP:{port}", "-sTCP:LISTEN"],
        capture_output=True,
        text=True,
        check=False,
    )
    return [int(x) for x in out.stdout.split() if x.isdigit()]

Then send SIGTERM and re-check the LISTEN PID list before escalating to SIGKILL.

Resources

Prefer using scripts/kill_port_listener.sh for reliable “kill only LISTEN” behavior.

Delete unused example resources if present.