0

apacheのデフォルトのエグゼキュータを使用してコマンドラインを実行するコードを書いています。終了コードを取得する方法を見つけましたが、プロセスIDを取得する方法が見つかりませんでした。

私のコードは:

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

ProcessIDを取得するにはどうすればよいですか?

4

2 に答える 2

3

apache-commons APIを使用して(または基盤となるJava APIを使用して)プロセスのPIDを取得する方法はありません。

「最も簡単な」ことは、プログラム自体が生成する出力で何らかの形でPIDを返すように、外部プログラムを実行することです。そうすれば、Javaアプリでそれをキャプチャできます。

JavaがPIDをエクスポートしないのは残念です。これは、10年以上にわたって機能要求でした。

于 2013-03-24T17:14:33.650 に答える
1

Java9以降でProcessオブジェクトのPIDを取得する方法があります。ただし、Apache Commons ExecでProcessインスタンスにアクセスするには、文書化されていない内部を使用する必要があります。

CommonsExec1.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);
于 2018-09-18T09:57:13.693 に答える