1

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?

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
Rivi
  • 791
  • 3
  • 15
  • 23

2 Answers2

4

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.

ddewaele
  • 22,363
  • 10
  • 69
  • 82
  • For example, this will cause the PID to be the first line printed : `/bin/sh -c 'echo $$ && exec program args'` – Hamy Oct 07 '15 at 14:13
2

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);