0

I have a shell script that spawns a java process that I'd like to wrap in a wrapper for use with monit.

I've tried the monit recommendation of

#!/bin/bash

name=`basename $1`
case $2 in
    start)
       echo $$ > /var/run/service.pid;
       exec 2>&1 $1 1>/var/log/$name.stdout
       ;;
     stop)
       kill `cat /var/run/service.pid` ;;
     *)
       echo "usage: <path to app> {start|stop}" ;;
 esac

Where I'd use it like wrapper.sh /usr/sbin/cmd start

When I do this, I see 2 procesess spun up. One is the exec in the wrapper, and the other is my java process.

However, the pid of $$ is that of the /usr/sbin wrapper and not of the actual java process. So if I "stop" the service or kill that pid, then the java process gets orphaned.

On the other hand, if I run /usr/sbin/cmd in the foreground and then kill it, it does kill the child process.

devshorts
  • 8,572
  • 4
  • 50
  • 73
  • 1
    If you `exec` the java process as the script aove dows, said java process will replace the shell process running the wrapper and thus will keep the same PID. Your problem is that the java process further forks other processes. – lcd047 Jun 19 '15 at 04:31
  • Thanks, this was the key I needed. In the /sbin command that execs my java process I needed to also add `exec` before the java invocation so that it would also use the same pid. Now in my sbin wrapper i have `exec java ...` and it all works great. Thanks! – devshorts Jun 19 '15 at 16:19

1 Answers1

2

You can't grab the pid before you run the command, but you can use $!. Also, I would suggest you use nohup. So something like

nohup $1 > /var/log/$name.stdout 2>&1 &
echo $! > /var/run/service.pid
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249