# Safe Port Kill

> 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.

- Skill: `tankygranny05/safe-port-kill` (Agent Skill, multi-file: 2 files)
- Install (CLI): `npx skillmds@latest add tankygranny05/safe-port-kill`
- Raw SKILL.md: https://api.skillmd.com/api/skills/tankygranny05/safe-port-kill/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: tankygranny05 (https://skillmd.com/u/tankygranny05)
- Updated: 2026-09-10
- Page: https://skillmd.com/skills/tankygranny05/safe-port-kill

---


# 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.

