How to prevent my java application from opening twice or more simultaneously?

Asked

Viewed 57 times

0

I am developing a project, in which I need to prevent the user to run the application more than once at the same time, that is, if the application is already running instead of running again it should inform the user that it is already running.

  • via Windows API has to take the list of running processes, certainly will have a process running with the name of your application, so would just take the processes and check which name matches your application, if it is already in the list give an alert and then an Exit

1 answer

1


There are two ways to do this, the two ways have to return the running processes so you can compare and check if your program is already running...

easier way(I don’t know, I don’t like it much, but it’s an alternative), you can run a exec to call the tasklist.exe, if you have in linux maybe a ps -ax, but solo windows would look something like this for ex

try {
    String line;
    Process p = Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
    BufferedReader input =
            new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((line = input.readLine()) != null) {
         System.out.println(line); 
    }
    input.close();
} catch (Exception err) {
    err.printStackTrace();
}

Inside the while will be shown each existing running process, you will have to organize that output, I believe using the tasklist.exe /fo csv /nh leave the output in a simpler format to create delimiters, surely you will have to treat the output, after the output treated just compare, ex:

if("seuprograma.exe".toUpperCase().equals(line).toUpperCase())) {
                        result = true;
                        break;
            }

The way I find more interesting and that would certainly be my choice is to take the processes via API, in windows I recommend using the JNA with the Java Native Access it is possible to read the Kernel32.dll windows and use the core classes of Microsoft

Example with JNA:

public static boolean ChecarPrograma() {
    try {
        Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);
        Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
        boolean resultado = false;
        WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
        try {
            while (kernel32.Process32Next(snapshot, processEntry)) {
                if ("Meuprograma.exe".toUpperCase().equals(Native.toString(processEntry.szExeFile).toUpperCase())) {
                    resulto = true;
                    break;
                }
            }
        } finally {
            kernel32.CloseHandle(snapshot);
        }
        ModManager.debugLogger.writeMessage("MeuPrograma.exe " + (resultado ? "Está" : "não Está") + "em execução");
        return result;
    } catch (Throwable t) {
        ModManager.debugLogger.writeErrorWithException("Exceção de acesso nativo crítica: ", t);
        ModManager.debugLogger.writeError("O Mod Manager relatará que o programa não está sendo executado para continuar as operações normais.");
        return false;
    }
}

Understanding what’s going on:

Take a look at this part of the code here kernel32.CreateToolhelp32Snapshot, checks in the windows documentation what this function does:

Takes a snapshot of the specified processes, as well as the heaps, modules, and threads used by these processes.

translating:

Tira uma captura instantânea dos processos especificados, bem como os heaps, módulos e threads usados por esses processos.

Now look at the link above and check in the documentation what is said about the parameter TH32CS_SNAPPROCESS:

Translation of the part that matters:

Inclui todos os processo do sistema no snapshot...

And finally, inside the While he’s making a Process32next, once again looking at the documentation we can note that this function is responsible for retrieving the information about the next process recorded in a snapshot...

I think that’s it, choose which path you find most interesting for your project...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.