I killed the process I started. The port stayed taken.

I killed the process I started. The port stayed taken.

●2 ●38 ●102
calendar_today • schedule1 min read

EADDRINUSE right after you stopped the server usually has one cause: the process you launched is not the process holding the socket. I reproduced it on my own machine with the wrapper shape npm run dev uses, a shell that starts the real server as a child and waits: bash -c 'python3 -m http.server 8098 & wait'. lsof -ti :8098 returned the child's PID, not the parent's. I killed the parent. The child was reparented, kept listening, and lsof returned the same PID as if nothing had happened.

The fix is to ask the socket table instead of the process table, and to look before you shoot:

PID=$(lsof -ti :8098 | head -n 1)
ps -p "$PID" -o comm=
kill "$PID"
sleep 5
kill -0 "$PID" 2>/dev/null && kill -9 "$PID"

The ps -p line exists because "which PID" is not "safe to kill". On a shared box, the thing on 5432 might be a database mid-migration. Plain kill sends SIGTERM, which lets the process flush and close its socket; on my run it was enough, and SIGKILL never fired. If the bind still fails with no PID left, that is TIME_WAIT, and the answer is a minute of patience.

Port validation, the ss fallback for boxes without lsof, and the escalation loop are in the script that frees a port by killing whatever holds it.


I bundled the scripts I copy onto every new server, plus 10 bonus ones, into the Production Bash Toolkit. 30-day refund if it isn't useful.

Want more #devops & #linux deep dives?

Join 6,093+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

1 Comment

0 votes

More Posts

A deploy guard that passes with no token

BashSnippets - Nov 24

sed 's/port/listen_port/g' rewrote four lines of a four-line config

BashSnippets - Oct 1

I Got Tired of Googling the Same Bash Commands, So I Built This. . .

BashSnippets - May 6

I deleted 44.6 GB and df moved by 5

BashSnippets - Nov 10

Every disk-alert script I had piped into a command this machine does not have

BashSnippets - Oct 15
chevron_left
3.8k Points • 142 Badges
North America • bashsnippets.xyz
79Posts
38Comments
14Connections
Linux user who got tired of Googling the same bash commands every time I sat down at a terminal. Sta... Show more

Related Jobs

View all jobs →

Commenters (This Week)

2 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!