ProcessHandle::onExit behavior

Chris Hegarty chris.hegarty at oracle.com
Tue Mar 7 10:37:46 UTC 2017


Sander,

> On 6 Mar 2017, at 15:46, Sander Mak <sander.mak at luminis.eu> wrote:
> 
> I was trying to get an example to work with the new ProcessHandle API. My goal was to wait on another process (Spotify) to terminate before printing something to the console:
> 
> ProcessHandle handle =
>        ProcessHandle.allProcesses()
>          .filter(h -> h.info().commandLine().map(cmd -> cmd.contains("Spotify")).orElse(false))
>        .findFirst()
>        .orElseThrow(() -> new IllegalArgumentException("No matching handle found"));
> 
> System.out.println(handle.info());
> 
> ProcessHandle completed = handle.onExit().get();
> System.out.println(completed.isAlive());
> 
> However this code doesn't wait on `handle` to be terminated, as the JavaDoc of onExit led me to believe: "Calling onExit().get() waits for the process to terminate and returns the ProcessHandle.". What I expected: the get() call blocks until I terminate the Spotify process. Instead, it runs to completion and prints true for the `isAlive` call in the end.  Am I missing something?

This is indeed confusing. ProcessHandle::onExit uses waitpid on “unix”, so
is only capable of waiting on child processes. In your code, you use
ProcessHandle::allProcesses to retrieve a handle to a non-child process.
Running a similar program on Linux, ECHILD can be observed as the error
returned from waitpid, which bubbles up as a ‘0’ exit code to onExit.

This is a bug. I filed:
  https://bugs.openjdk.java.net/browse/JDK-8176272

The spec should clarify this behaviour, or ...

The implementation could be updated to better handle “waiting” on non-child
processes. Possibly polling with `kill(pid, 0)`, or something else.

> Env: Java(TM) SE Runtime Environment (build 9-ea+157-jigsaw-nightly-h6122-20170221) on MacOS.
> 
> Also, first time posting to this list, I hope this is the right avenue for these questions.

This is the correct list for such issues.

-Chris.


More information about the core-libs-dev mailing list