Today I Learned

A Hashrocket project

Ready to join Hashrocket? Find Openings here and apply today.

Find (and kill) all processes listening on a port

To search for processes that listen on a specific port use the lsof or “List Open Files”. The -n argument makes the command run faster by preventing it from doing a ip to hostname conversion (it’s still pretty slow). Use grep to show only lines containing the word LISTEN.

lsof -n | grep LISTEN

A SIGNIFICANTLY FASTER way. Is to use the -i option to filter for a specific port:

lsof -i tcp:[PORT]

To kill all processes listening on a specific port use:

lsof -ti tcp:5900 | xargs kill

The -t command returns only the PID, exaclty for the purpose of piping it somewhere, and the xargs executes kill on each line returned.

If the process is more persistent, and kill did not work, try kill -9 to kill it more aggressively.