Monitor shell script with monit

1k views Asked by At

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.

1

There are 1 answers

0
Elliott Frisch On

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