1

Is it possible to kill a process using port that it is listening on in java?
I know on linux you can use fuser command but I would prefer to do it programatically and make it OS universal.

Grimalkin
  • 107
  • 12
  • You can just use that command in any OS you want and run it in Java with the Java process API Link: https://www.baeldung.com/java-process-api – NLxDoDge Aug 16 '22 at 09:52
  • I suppose It is an option the thing is you have to use different command for different operating systems – Grimalkin Aug 16 '22 at 09:59
  • 2
    @NLxDoDge No you can't. `fuser` doesn't exist on all operating systems. – user207421 Aug 16 '22 at 09:59
  • Look how others are trying to get the running processes in java. None of these solutions can check whether a socket is in use. https://stackoverflow.com/questions/20472639/how-to-get-list-of-running-processes-with-java – Queeg Aug 16 '22 at 10:22
  • @HiranChaudhuri I have decided to use `process.pid()` and save it into databaes since. It causes some other problems that is why I wanted to avoid that but it is the most universal one – Grimalkin Aug 16 '22 at 10:33
  • The way we do it is by printing a nice error message saying the port is already in use and where to change the port number if required. – NLxDoDge Aug 17 '22 at 08:56

2 Answers2

1

I have decided to use KISS rule and just timeout process my program starts instead of performing dangerous OS commands

Grimalkin
  • 107
  • 12
0

Call netstat -p. Netstat will print the pid if you have sufficient privileges. Next call kill to terminate the process.

You can do that manually, you can as well script it or code it in Java.

Queeg
  • 7,748
  • 1
  • 16
  • 42
  • This answear is great, but It won't work on windows, I want it to be universal. – Grimalkin Aug 16 '22 at 10:14
  • 1
    Netstat exists on Windows, however the command line option may be different. Also you have to use taskkill instead of kill. I'm afraid there is no platform independent solution here. You also did not specify you need such a solution. – Queeg Aug 16 '22 at 10:16
  • Yes I forgot to add that, You are absolutely correct – Grimalkin Aug 16 '22 at 10:18