-2

I have a bash script that starts a java application using an until block. It gets the exit code from the java application and if it gets a known shutdown exit code the bash script exits, otherwise, it restarts the java application

$CMD=java -jar program.jar
until $CMD; do
  EXIT=$?
  if [ $EXIT == 2 ]
  then
       exit
  fi
  sleep 10
done

This works fine, but I've got another application that needs to be aware of the pid of the process, up to this point, i've been using pgrep, but the powers that be don't like this idea. They want me to write the PID to a pid file. How can I modify my script so that it writes the pid to a pid file and removes it when it ends?

Thank you.

MABeatty1978
  • 115
  • 1
  • 3
  • 14
  • 1
    First, unless you start it in the background, which you aren't actually doing, your `do` doesn't even begin until after it already exited. – Charles Duffy Sep 12 '17 at 19:08
  • 1
    Second, `$CMD=java -jar program.jar` doesn't assign your command line to the variable `CMD`. And even if you fixed the syntax so it *was* an assignment, it'd fall afoul of the bugs described in [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050). – Charles Duffy Sep 12 '17 at 19:08
  • 3
    BTW, your "powers that be" are leading you astray. You shouldn't use `pgrep` *or* pidfiles -- you should use POSIX advisory locking, a la `flock`. A flock-style advisory lock is automatically cleared on program exit, even if it's a hard shutdown / power loss scenario. There's no chance of collisions, as there is with PIDs. There's no chance of similar- or like-named processes happening to match accidentally. – Charles Duffy Sep 12 '17 at 19:09
  • 1
    ...and you can always look up the PID(s) of process(es) holding a lock with `fuser` or similar tools. Even better would be to use a proper process supervision system (your OS almost certainly includes one out-of-the-box, such as systemd, upstart or launchd) to run your daemon for you -- that way *that tool* can be responsible for ensuring that there's only one instance, automatically restarting it if that's desired, and looking up the PID on request. – Charles Duffy Sep 12 '17 at 19:13

1 Answers1

0

A naive but common implementation might look like:

java -jar program.jar & pid=$!
echo "$pid" >/path/to/file.pid
wait "$pid"

Note the & -- this puts your program in the background. Unless you background it, there is no active PID to collect from a subsequent line in your script, because the interpreter waited for the program to exit before going on to a subsequent line.

But don't do this at all. See my comments on the question.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441