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.
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.
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();
}
}
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.
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.