Java ProcessHandle.Info.totalCpuDuration() returning very little data

Viewed 121

When does the 'Optional<Duration> totalCpuDuration();' method of ProcessHandle.Info return information?

I've tried with and without sudo, doesn't seem to make much difference; either way only the current process returns non-empty value. The documentation does not say much.

What stops the JVM stdlib running under sudo (on MacOS or Linux) from getting that information? Is it just not implemented? Would getting that info be too slow?

2 Answers

This has nothing to do with permissions, at least on MacOS: it's just not implemented (as of May 2021).

For linux, the code seems to read the cpu time via the proc fs for all processes, or at least try to, permissions might apply.

For MacOS, it only reads info for the current process. It's hardcoded: if (pid == getpid()) { ... }; no attempt is made to get this info from other processes.


MacOS:

https://github.com/openjdk/jdk15u/blob/master/src/java.base/macosx/native/libjava/ProcessHandleImpl_macosx.c

Linux:

https://github.com/openjdk/jdk15u/blob/master/src/java.base/linux/native/libjava/ProcessHandleImpl_linux.c


And here's an answer with some code to implement a workaround with Java and shell exec:

https://stackoverflow.com/a/36381244/336356

An alternative way of getting Total CPU Duration of your process is this

ProcessHandle processHandle = ProcessHandle.of(<system pid>).get();
ProcessHandle.Info processInfo = processHandle.info();
long timeDiff = Instant.now().getEpochSecond() - processInfo.startInstant().get().getEpochSecond();

This works for any process that user has access to, not just current process.

Related