File lock to check one service execution. How reliable is it?

I am deploying a small service on a UNIX system (AIX). I want to check if there is an active instance of this service at startup. How reliable is the implementation of such a check?

  • Try to get a file lock (w / FileChannel

    )
  • If it succeeds, keep blocking and continue executing
  • If the crash is complete, exit and discard starting the main body.

I am aware of software such as the Tanuki shell, however I am aiming for a simpler (possibly not portable) solution.


EDIT: Regarding the PIDFILE (s): I want to avoid using them if possible, since I have no administrator rights on the machine, no knowledge of AIX shell programming.

+2


a source to share


3 answers


An alternative could be to bind to a specific port on the server using 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 great on any platform.

+2


a source


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



As the name suggests, the content of this file is the PID of the service. This allows you to get a form of error recovery when, when starting a service and detects that a PID file exists, instead of just exiting it directly, it can check if a process exists with that PID, and if not, which means the service daemon crash, start up, and try to recover from a previous crash.

+3


a source


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

Check if the file exists. If so, alert the user immediately and exit. Otherwise, create this file and continue.

0


a source







All Articles