我正在写这个服务器,我想检查相同的程序是否已经在运行,如果正在运行关闭程序.
说我运行ServerA
然后我运行ServerB(这是相同的服务器)
我想关闭ServerA,以便ServerB可以成功运行.
最佳答案 好吧,我设法做到这样……
public static void main(String[] args){
String PIDtoKill = readPIDFile();
if(!PIDtoKill.isEmpty())
killPID(PIDtoKill);
saveThisPIDtoFile();
}
使用方法….
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();
}
}