4

I'm writing this server, and I want to check if the same program is already running, if is running close the program.

Say I run ServerA

Then I run ServerB (which is the same server)

I want to close ServerA so ServerB can run successfully.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Jose Lopez
  • 374
  • 1
  • 2
  • 11

3 Answers3

1

Okay I manage to do it like so...

public static void main(String[] args){
    String PIDtoKill = readPIDFile();
    if(!PIDtoKill.isEmpty())
        killPID(PIDtoKill);
    saveThisPIDtoFile();
}

Method used....

private static String readPIDFile() {
    try {
        for (String line : Files.readAllLines(Paths.get("C:\\Users\\MyUser\\Desktop\\PIDsRunning.txt")))
            return line;
    }
    catch (IOException e1) {
        e1.printStackTrace();
    }
    return "";
}

private static void saveThisPIDtoFile() {
    String pid = ManagementFactory.getRuntimeMXBean().getName();
    pid = pid.substring(0, pid.indexOf("@"));

    List<String> lines = Arrays.asList(pid);
    Path file = Paths.get("C:\\Users\\MyUser\\Desktop\\PIDsRunning.txt");

    try {
        Files.write(file, lines, Charset.forName("UTF-8"));
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}

private static void killPID(String pIDtoKill) {
    try {
        Runtime.getRuntime().exec("taskkill /F /PID " + pIDtoKill);
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}
Jose Lopez
  • 374
  • 1
  • 2
  • 11
  • Keep in mind if you take this route that for cross-platform support (past Windows) you'll need to find the OS and Call an OS appropriate equivalent command to 'taskkill' – parabolah Feb 04 '17 at 06:20
  • 1
    thanks , I know but this is just for devoloping purposes, and maybe i leave it as it is, cuz this program will be running on a windows VPS. – Jose Lopez Feb 04 '17 at 10:03
0

In case you want to close the program if it is open
You can go for:
System.exit(0);
There are many other exit codes but 0 seems to suit your requirement.

  • 1
    Yes, but I dont want to close the current program, I want to close the program that ran first so that the newer program can run – Jose Lopez Feb 04 '17 at 09:57
0

Using the system to kill the process by pid is one solution.

One can use RMI (Remote Method Invocation) to create single instance applications, or in your case send a kill call so the application can terminate on its own. (A graceful termination, requiring the app to be still functioning.)

You could also use an OSGi container: that play with module life cycles the best.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138