Patricia Sauer - Authentic Programming

Killing a process in one line

A hacker in a hoodie

It happened to all of us: We start a service and the command line tells us 'Address already in use'. Awesome. By which service? Which process do I have to kill? I can't find it 🤬

So let's have a look at how we can kill the unknown process in just one line 😏

The magic command

In short: The magic command is kill -9 $(lsof -t -i :portNumber) where you have to replace "portNumber" with the number of the blocked port. For example, if port 8080 was blocked, the command would be kill -9 $(lsof -t -i :8080).

What the command does under the hood

Lsof stands for "list open files". When you are enterin just lsof in your terminal, the output might be huge.

The -t option makes the lsof command just print the PID (process id). Whereas the -i filter selects the listing of files any of whose Internet address matches the address specified in i. In our case, we want to filter for the process running on port 8080 and therefore set the filter to ":8080". This results in one or multiple PIDs. Multiple PIDs will be printed when multiple processes are involved in blocking the port.

The kill command terminates a specific process. The -9 option is used to send a signal to the process to terminate it. The signal used is the "SIGKILL" signal which is the most forceful way to terminate a process. This signal cannot be ignored or blocked by the process and it will immediately stop the process. You could also use the -15 option instead which sends a "SIGTERM" signal. This allows the process to terminate gracefully, giving it a chance to clean up and save its state before exiting.

We are passing the result of lsof -t -i :portNumber (i.e. the process ID of the process blocking the specific port) to the kill command by surrounding it with $(). The kill -9 command will then terminate the process with the found process ID.

Recap

From time to time, we are annoyed by processes blocking a port which we want to use.

In this article we learned

  • how to terminate a process blocking a specific port (kill -9 $(lsof -t -i :portNumber))
  • what the used commands do behind the scene:
    • lsof -t -i :portNumber will get the process ID of the process blocking the specified port
    • kill -9 will terminate the process forcefully
    • kill -15 will terminate the process gracefully, giving it a chance to clean up and save its state before exiting

Watch it on YouTube

You can watch me explaining how to kill a process in one line in this video:

Liked this article?

Buy Me A Coffee

© 2018 - 2024 Patricia Sauer