Search code examples
javajenkinsdaemon

How do I get the PID of this Java app?


I have a java app on my (Ubuntu) server. If I do this, then it starts correctly:

/usr/bin/java -cp /home/jenkins/veta/lily.jar com.sugarapp.lily.Main 

but I don't know how to get its PID. I don't know how to stop it with an init.d script.

I have a different app, written in Clojure, and for it I was able to write an init.d script that works great. So I tried to refashion that init.d script for my Java app, and this is what I got:

WORK_DIR="/home/jenkins/veta"
NAME="lily"
JAR="lily.jar"
USER="jenkins"
DAEMON="/usr/bin/java"
DAEMON_ARGS=" -cp /home/jenkins/veta/lily.jar com.sugarapp.lily.Main"

start () {
  echo "Starting lily..."
  if [ ! -f $WORK_DIR/lily.pid ]; then
    /sbin/start-stop-daemon --start --verbose --background --chdir $WORK_DIR --exec $DAEMON --pidfile $WORK_DIR/lily.pid --chuid "$USER" --make-pidfile -- $DAEMON_ARGS
  else
    echo "lily is already running..."
  fi
}

stop () {
    echo "Stopping lily..."
    /sbin/start-stop-daemon --stop --exec $DAEMON --pidfile $WORK_DIR/lily.pid
    rm $WORK_DIR/lily.pid
}

But this doesn't work. Although the PID in $WORK_DIR/lily.pid changes every time I run the script, no process with that PID ever seems to run. If I try:

ps aux | grep java

I don't see this app, nor if I try using the PID.

So is there a way I can use the first command, but somehow capture the PID, so I can store it for later?

I just want a reliable way to stop and start this app. That can be by PID or some other factor. I'm open to suggestions.

UPDATE:

Maybe my question is unclear? Something like jps or ps will give me too many answers. If I do something like "ps aux | grep java" I'll see that there are 5 different java apps running on the server. The start-stop-daemon won't know which PID belongs to this particular app, nor can I figure out what I should feed into my init.d script.


Solution

  • If you want the pid from the command line, this might work:

    myCommand & echo $!
    

    Which I copied from the accepted response to a very similar topic in ServerFault: https://serverfault.com/a/205504