I've two Java 11 methods that check whether a process for a given PID is running:
public static final boolean isProcessRunning( final long pid ) {
Optional< ProcessHandle > optionalProcess = ProcessHandle.of( pid );
return optionalProcess.isPresent() && optionalProcess.get().isAlive();
}
public static boolean isProcessRunning2( final long pid ) {
return ProcessHandle.allProcesses()
.filter( p -> p.pid() == pid )
.anyMatch( p -> p.isAlive() );
}
When checking multiple PIDs on Linux clients, I'm getting sometimes different results for certain PIDs, where the first implementation always returns true
and the second one always false
.
Checking some "false positives" with shell command ps -ef | grep <pid>
shows that first implementation seems to be wrong, the OS doesn't know about these processes neither.
Assumably the second implementation is always right but seems to be very inefficient.
What's wrong with the first implementation and how can I fix it?