Monday, March 8, 2010

Generating a Tomcat PID file on the fly

I needed to use jsvc to stop tomcat processes, something that required a PID file containing the Process ID of the tomcat being stopped. My first alternative was to use jsvc to start Tomcat and specify the PID file to generate. Looking at the myriad of command line options that jsvc needed, I decided to stick to the provided startup.sh.

This left me with the option of generating the PID file after Tomcat had been started normally. For this, I used the lsof command of which I found an excellent reference. This is the command I used:

lsof -t -l -a -i TCP:$1 -a -c java > $tmp_file && /usr/local/bin/jsvc -stop -pidfile $tmp_file org.apache.catalina.startup.Bootstrap

The line above consists of two commands, one where lsof writes Tomcats PID into a file and the other where jsvc uses that file to shutdown Tomcat. Here is a break down of the options to lsof.

-t output the PID only
-l show ports that are in listening mode
-a and (this enables a boolean relation to be constructed between options)
-i TCP:$1 show a process with an open TCP port held in the shell input variable
-a and
-c java show processes with the name java

1 comment:

  1. The first part of the command (which invokes lsof) can match multiple processes - the server process and established connections by other java programs to the server processes.

    A better alternative is:
    lsof -a -i TCP:$1 -c java | grep LISTEN | awk '{print $2}'

    ReplyDelete