Verify if a process is running using its PID in JAVA

Issue

I’m currently building an application in JAVA where there can be only one execution. So I’m currently using a lock file in which I write the PID of the current execution.

So whenever this application will start, it will open the file (if it exists) and try to detect if the PID written in the file is actually running.

This prevent the problem where my app crash before unlocking the file.

I need this to work both on windows (XP,7 or 8) and linux (all the users are on debian based distros).

Here’s some code to give you a better picture of what I want to do :

//get the PID from the file
int pidValue = new FileReader(file).read();

//get the OS type
String os = System.getProperty("os.name").toLowerCase();

//Check PID depending of OS type
if( os.contains("nux") || os.contains("nix") ){
/*
 * Check PID on Linux/Unix
*/
} else if ( os.contains("win") ) {
/*
 * Check PID on Windows
 */
}

I have tried to find documentation on the subject, but I didn’t manage to find anything useful yet.

Thank you very much.

Solution

On posix systems the typical way to query if a pid is running is to send it a null signal e.g. kill(pid, 0). If the call succeeds the process exists; if it returns ESRCH it does not. This is naturally subject to unavoidable race conditions which amount to much less in reality than they do in theory. Less uniform ways are to read the /proc file system (if the OS has one) which is more work, amounts to the same thing, and is still subject to the same race conditions.

Note that pid lockfile technique can be two-tiered. That is, the running process creates the file, locks it, and writes its pid. It holds the lock for the duration of its run and thus this pretty much does away with the above need to query whether the process is running because if the process crashes the file lock will be automatically released even though the file still exists. The logic goes like this:

if file exists
   if can get lock
       prev instance died unnaturally
       continue with this new process
   else
       instance already running
else
   good to go, continue with new process

This technique also has race conditions.

I don’t remember enough Java to say whether it has wrappers for kill or file locking syscalls like flock, lockf and fcntl required to implement this scheme.

Answered By – Duck

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published