Verify if a process is running using its PID in JAVA

后端 未结 3 632
不思量自难忘°
不思量自难忘° 2020-12-19 13:00

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.

3条回答
  •  情话喂你
    2020-12-19 13:25

    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.

提交回复
热议问题