views:

53

answers:

3

Hello,

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, however, 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.

A: 

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.

nc3b
+3  A: 

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.

janneb
+1  A: 

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.

ninesided
@ninesided What if any other service or application on that system also use the same port and is running when the OP tries to run his service?
Yatendra Goel
If you have other services that bind to ports running on your server I would hope that you know what they are and avoid those port numbers. Some services bind to random free port, but they nearly always pick that number from a defined range. I highly doubt that you would run out of ports in most real world situations.
ninesided
I've ended using this. Nice approach indeed!
Camilo Díaz