Share Process / Thread

75 views Asked by At

I am facing a problem regarding Process and Threads. My Scenario is:

  • My Java Application, call it 'Starter-App', starts another exe Application (Diagnosis.exe) with ProcessBuilder within a named Thread:

    Thread startGXThread = new Thread(new Runnable() {  
        @Override       
        public void run() {
            try {
                ...
                File gxExe = new File(pathToGX); // Path to Diagnosis.exe
                gxp = pb.start();
                gxp.waitFor();
    
            } catch (IOException e) {
                LOG.error("Can't start module");
                LOG.error(e.getMessage(), e);
            } catch (InterruptedException e) {
                LOG.debug("thread interrupted. Destroy process");
                LOG.debug(e.getMessage(), e);
                if (gxp != null) {
                    gxp.destroy();
                    LOG.debug("process exit value: " + gxp.exitValue());
                }
            }
        }
    }, "diag_thrd");
    
  • Afterwards a jetty webserver (ServiceWebApp) is started with a webapp.

  • start chromium and 'Starter-App' listen when its closed.
  • Once chromium closes 'Starter-App' recognizes this and stops jetty and also terminate the startet application.Diagnosis.exe. This is done by:

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            stopAsync();
        }
    });
    
    public static void stopAsync() {
        Thread diag = getThread("diag_thrd");
        if (diag != null) {
            diag.interrupt();
        }
        if (gxp != null) {
            gxp.destroy();
            LOG.debug("process exit value: " + gxp.exitValue());
        }
    }
    

Question: I need to be able to stop the startet Diagnosis.exe from within the webapp and start it again, while still be able to destroy/shutdown the Diagnosis.exe once chromium stops within 'Starter-App'. I hope I could explain my problem and hope for suggestions.

2

There are 2 answers

1
Sonata On BEST ANSWER

Building on Anands answer, I think you need some form of IPC between the Diagnosis.exe and your Starter-App, using websockets, or a number of other options, for some ideas: How to have 2 JVMs talk to one another.

The webapp would send a request for restarting Diagnosis.exe to the Starter-App and the Starter-App would stay in charge of managing the application trio at all time.

2
Anand Vaidya On

I think there is a solution but a but tricky to implement.

You can always use *nix api's like ps kill #pid as explained in the example here Killing a process using Java

But your webserver has to know which PID's to look for. The only option I see to implement such thing is using sockets or webservices. So you keep track of what is the current pid of Diagnosis.exe process, and use that Id before killing.