splinter123
splinter123

Reputation: 1203

Java kill program if already running

I would like my java program to check whether another instance of it is already running, and kill it if this is the case (on a Windows platform). I'm doing this with the code

String CMD = 
        "wmic PROCESS where \"CommandLine like '%%MyProgram%%'\" Call Terminate";
Process process = Runtime.getRuntime().exec(CMD);

The code executes succesfully and kills the running program if it is found, however once executed it forces also the calling program to exit (there must be some hidden call to System.exit()). Is there a way for executing the command without exiting the calling program?

Upvotes: 0

Views: 2117

Answers (3)

nathanfranke
nathanfranke

Reputation: 991

try {
    ServerSocket ss = new ServerSocket(1044);
} catch (IOException e) {
    System.err.println("Application already running!");
    System.exit(-1);
}

Multi platform, 6 lines. The only catch is that the port 1044 (You can change it) must be open. Basically, running the program will establish a "server", but if the port is already a server, it was already started, and it will close.

Just remember that starting a server on the same port as another server is impossible, which we can use to our advantage.

Upvotes: 1

jlr
jlr

Reputation: 1530

You could leverage a Windows Service for that. You'll know only one instance will run + you can get it running with no users logged in (if desired). Use Apache Commons Daemon with procrun (if only meant for Windows):

http://commons.apache.org/proper/commons-daemon/index.html http://commons.apache.org/proper/commons-daemon/procrun.html

A SO reference for more options and exploration daemons and Java: How to Daemonize a Java Program?

Good luck!

Upvotes: 0

Tim Jansen
Tim Jansen

Reputation: 3368

As mentioned in the comments, the command will also kill the new instance. There are ways around it, like creating pid files to ensure only one instance is running. But that probably doesn't matter, because there are better ways to do the same.

Please check How to implement a single instance Java application and How to allow running only one instance of a java program

Upvotes: 1

Related Questions