乐闻世界logo
搜索文章和话题

How to kill a process running on particular port in Linux?

1个答案

1

In Linux, to terminate a process running on a specific port, follow these steps.

Step 1: Locate the Process ID (PID) Running on the Specific Port

You can use the netstat command or the lsof command to find the process ID (PID) of the process bound to a specific port. Here, I'll demonstrate both methods.

Using the netstat Command

  1. Open the terminal.

  2. Enter the following command, replacing <port> with the port number you are interested in:

    bash
    sudo netstat -nlp | grep :<port>

    The -nlp options mean: -n avoids DNS lookups, -l shows only listening ports, and -p displays the process ID and name.

Using the lsof Command

  1. Similarly, open the terminal.

  2. Enter the following command, replacing <port> with the port number you are interested in:

    bash
    sudo lsof -i :<port>

In the output of these commands, you can identify the corresponding PID. These outputs will show which process is utilizing the specified port.

Step 2: Terminate the Process

Once you have the PID, use the kill command to terminate it. If the normal kill command fails to stop the process, try using kill -9, which forcibly terminates the process.

  1. Use the following command, replacing <PID> with the PID of the process you want to terminate:

    bash
    sudo kill <PID>
  2. If the process does not terminate normally, use:

    bash
    sudo kill -9 <PID>

kill -9 sends signal 9 (SIGKILL) to the process, which is an ungraceful termination that does not allow the process to clean up resources. Therefore, it's best to use the command without -9 first.

Example

Suppose you want to terminate the process running on port 8080:

bash
sudo lsof -i :8080

Assume the output shows the PID as 1234. Then run:

bash
sudo kill 1234

If the process does not terminate, use:

bash
sudo kill -9 1234

These commands provide a quick and effective way to manage port conflicts or unnecessary service issues.

2024年8月14日 18:01 回复

你的答案