LifeOnNet
LifeOnNet

Reputation: 107

Java subprocess terminated by itself

My application uses some daemon subprocesses for subtasks. The subprocesses are launched using ProcessBuilder and working fine on their own, but then starting them as subprocesses every associated Process.isAlive() method return FALSE. As following, no access to process is possible.

Further investigation shows the subprocesses are not started at all (don't exist in Task Manager) with no error generated at all.

Upvotes: 0

Views: 283

Answers (2)

Sarel Botha
Sarel Botha

Reputation: 12700

Is the command really running? Often there are weird little issues when trying to run a program from inside Java.

For example, the PATH environment variable may not be set correctly so it fails to load a dependency.

Use this method to see if there is any console output and what the exit code is. This uses the old Runtime class instead of ProcessBuilder. It can probably be adapted to use ProcessBuilder.

public static void runExe(String[] command) throws IOException {
    Runtime runtime = Runtime.getRuntime();
    long start = System.currentTimeMillis();
    Process proc = runtime.exec(command);
    BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    try {

        while (true) {

            // enter a loop where we read what the program has to say and wait for it to finish
            // read all the program has to say
            while (br.ready()) {
                String line = br.readLine();
                System.out.println("CMD: " + line);
            }

            try {
                int exitCode = proc.exitValue();
                System.out.println("exit code: " + exitCode);
                // if we get here then the process finished executing
                break;
            } catch (IllegalThreadStateException ex) {
                // ignore
            }

            // wait 200ms and try again
            Thread.sleep(200);

        }

    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    long end = System.currentTimeMillis();
    System.out.println("Command took: " + (end - start) + "ms");
}

Upvotes: 0

Joni
Joni

Reputation: 111259

Daemons typically start a separate process and exit almost immediately, which makes checks like isAlive() useless.

Often the program will have a command line switch that make the program stay in the foreground, not becoming a daemon - use that if possible. Otherwise you'll need some other way of monitoring the daemon execution, for example using the daemon's PID file.

Upvotes: 1

Related Questions