javaapache-commons-exec

Getting process ID with java apache default executor


I'm writing a code that runs a commandline using default executor of apache. I found the way to get the exit code but I couldn't found the way to get the process ID.

my code is:

protected void runCommandLine(OutputStream stdOutStream, OutputStream stdErrStream, CommandLine commandLine) throws InnerException{
DefaultExecutor executor = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdOutStream,
            stdErrStream);
    executor.setStreamHandler(streamHandler);
    Map<String, String> environment = createEnvironmentMap();
try {
        returnValue = executor.execute(commandLine, environment);
    } catch (ExecuteException e) {
       // and so on...
        }
        returnValue = e.getExitValue();
        throw new InnerException("Execution problem: "+e.getMessage(),e);
    } catch (IOException ioe) {
        throw new InnerException("IO exception while running command line:"
                + ioe.getMessage(),ioe);
    }
}

What should i do in order to get the ProcessID?


Solution

  • There is no way to retrieve the PID of the process using the apache-commons API (nor using the underlying Java API).

    The "simplest" thing would probably be to have your external program executed in such a way that the program itself returns its PID somehow in the output it generates. That way you can capture it in your java app.

    It's a shame java doesn't export the PID. It has been a feature-request for over a decade.