HomeTeamContact

How to kill a process running in windows using port number

By Bijees Raj
Published in Java
December 27, 2022
1 min read
How to kill a process running in windows using port number

How to kill a process running in windows using port number

2 Options for exiting/killing a process running in Windows

  1. Using Command Prompt

    netstat -ao -p tcp | findstr "3000"
    

    Where ‘3000’ is the port number in which the process is running

    obtain the PID (Process ID) by running the above command , then use the below command to kill the process with PID

    taskkill /pid <PROCESS_ID_HERE>
    ex: taskkill /pid 8087
    
  1. Using a Java Program

    Create a java program with file name TaskKiller.java

import java.io.IOException;
import java.util.Scanner;

public class TaskKiller {

     public static void main(String[] args) throws IOException {
            System.out.println("Kill the Process Running On port  : ");
            Scanner sc = new Scanner(System.in);
            String port = sc.next();
            System.out.println("Looking for Process Running on port : " + port);
            Process process = Runtime.getRuntime().exec("cmd /c netstat -ao -p tcp | findstr \""+port+"\"");
            Scanner scanner = new Scanner(process.getInputStream());

            int count = 0;
            String processId = null;

            while (scanner.hasNext()) {
                String value = scanner.next();
                if(count == 4) {
                    System.out.println("Found Process Running On port :"+port);
                    System.out.println("ProcessId =" +value);
                    processId = value;
                }
                count++;
            }


            if(processId !=null && Integer.parseInt(processId)>0) {
                System.out.println("Killing the Process");
                Runtime.getRuntime().exec("cmd /c taskkill /pid " + processId + " /f");
                System.out.println("Process running on port "+port+" has been killed.");
            }
            if(processId ==null){
                System.out.println("No Process found on port "+port);
            }
            scanner.close();
            sc.close();

    }
}

You could create a windows batch file (.bat) and trigger the Java Program.

run-task-killer.bat

@echo cd\
cd c:
cd c:\code\
javac TaskKiller.java
java TaskKiller

@echo ----------
@echo Completed
@pause
  1. Run your application and the scheduled task will begin running at the specified interval.

Happy Coding !


Tags

#OS#Java
Previous Article
How to use Interceptors in Nest.js
Bijees Raj

Bijees Raj

Developer | Architect

Table Of Contents

1
How to kill a process running in windows using port number
2
2 Options for exiting/killing a process running in Windows

Related Posts

Integration test with mongodb using testcontainers
December 30, 2022
1 min

Quick Links

About UsContact Us

Social Media