开发者

Locking a file to verify a single execution of a service. How reliable?

I am deploying a little service to an UNIX(AIX) system. I want to check if there is no active instance of that service running when starting it. How reliable is to implement that check like this?

  1. Try to acquire a lock on a file (w/ FileChannel)
  2. If succeeds, keep lock and continue execution
  3. If fails, exit and refuse to run the main body

I am aware of software like the Tanuki wrapper, how开发者_JAVA技巧ever, I'm longing for a simpler(maybe not portable) solution.


EDIT: Regarding PIDFILE(s): I want to avoid using them if possible, as I don't have administrative rights on the machine, neither knowledge in AIX's shell programming.


An alternative would be to bind to a specific port on the server using a ServerSocket, if the port is in use, then your service is already running:

int port = 12345;

try { 
    java.net.ServerSocket ss = new java.net.ServerSocket(port); 
} catch (java.net.BindException ex) { 
    System.err.println("service is already running and bound to port "+port);
    System.exit(1);
} 

The advantage of this approach is that it works nicely on pretty much any platform.


Traditionally on Unix systems this is done by creating a file /var/run/nameofservice.pid. On startup you check whether such a file exists, if not, create it and continue. Then when the service is shut down, the pid file is deleted.

As the name implies, the contents of this file is the PID of the service. This allows a form of error recovery, in that when the service starts and detects that a PID file exists, instead of just quitting outright, it can check whether a process with that PID actually exists, and if not, which implies that the service daemon has crashed, start and try to recover from the previous crash.


Why not use a pidfile ? http://www.linux.com/archive/feed/46892

Check if a file exists. If so, warn the user and exit immediately. Otherwise create that file and continue running.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜