How to monitor external process ran by ProcessBuilder?

前端 未结 3 1741
眼角桃花
眼角桃花 2020-12-19 08:47

This should be rather simple, but I don\'t see anything helpful in JavaDocs.

What I need is to run some external process from my Java code and then be able to monito

3条回答
  •  天涯浪人
    2020-12-19 09:10

    I'm not sure I'm understanding the question but one way to do this is to call process.exitValue();. It throws an exception if process has not yet terminated:

    /**
     * Returns the exit value for the subprocess.
     *
     * @return  the exit value of the subprocess represented by this 
     *          Process object. by convention, the value 
     *          0 indicates normal termination.
     * @exception  IllegalThreadStateException  if the subprocess represented 
     *             by this Process object has not yet terminated.
     */
    abstract public int exitValue();
    

    If you don't mind a hack, you can do something like the following if you are working on a ~Unix system which uses the UNIXProcess class. This does use reflection however:

    ProcessBuilder pb = new ProcessBuilder("/bin/sleep", "5");
    Process process = pb.start();
    // open accessability of the UNIXProcess.hasExited field using reflection
    Field field = process.getClass().getDeclaredField("hasExited");
    field.setAccessible(true);
    // now we can get the field using reflection
    while (!(Boolean) field.get(process)) {
        ...
    }
    

提交回复
热议问题