Question

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?

Was it helpful?

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.

OTHER TIPS

There is a way to retrieve the PID for a Process object in Java 9 and later. However to get to a Process instance in Apache Commons Exec you will need to use some non-documented internals.

Here's a piece of code that works with Commons Exec 1.3:

DefaultExecutor executor = new DefaultExecutor() {
    @Override
    protected Process launch(final CommandLine command, final Map<String, String> env, final File dir) throws IOException {
        Process process = super.launch(command, env, dir);
        long pid = process.pid();
        // Do stuff with the PID here... 
        return process;
    }
};
// Build an instance of CommandLine here
executor.execute(commandLine);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top