look out honey 'cause I'm using technology

HOWTO: create a pidfile for a startup script

On the monit mailing list today someone asked how they could monitor a process that didn’t have a pidfile associated with it.  Without thinking I jotted this down, there’s likely a better way, but this should work and may be all I need for some init.d scripts for a couple of apps on ramon (the home server).  In the the beginning of the startup script, define the PIDFILE with the path and the cmd followed by the pid suffix and then just dump the PID number from the ps output into it:

export PIDFILE=/var/run/${1}.pid
ps -fe | grep ${1} | head -n1 | cut -d" " -f 6 > ${PIDFILE}

Once this is done, monit can monitor it just like it monitors any other process with a PID.  Later, for a shutdown hook, nuke the PIDFILE on the way out.

if [ -f ${PIDFILE} ]; then
rm ${PIDFILE}
fi
### rest of shutdown ###
exit 0

I think that should do it, anyone see a problem with that / a better way?



Related posts

  • stentor142
    This is not professional. Also this way script doesn't work every time because of sort of columns and the spaces before the PID numeber will not be every time 2 for your case.

    root 2783 1 0 14:23 ?
    root 32528 2940 0 21:31 ?
    root 32536 32528 0 21:31 pts/2
  • stentor142
    Sorry for the bad example, but it seems the field for the comments doesn't sorting anything. So, look at your console and see when you have 3 number PID, 4 and even 5 number PID how they are sorted.
  • parera10
    Hi,
    I had the same problem. I solved it doing this:

    In your init script, after launch the daemon in the "start" function you can use this:
    pidof $prog > $pidfile
  • shell

    #!/bin/sh

    vi newfile &
    PID_OF_VI=$!
    echo $PID_OF_VI>/var/run/.vipid
  • Mike Wyant Jr
    Even two years out that works for me. Thanks.
  • Jens
    to find out the process id, use pgrep instead of your "ps -fe | grep ${1} | head -n1 | cut -d" " -f 6 > ${PIDFILE}"

    Regards,
    Jens
  • Jens, this works great, thanks, I hadn't heard of pgrep:

    $ pgrep -u phil firefox
    10812
blog comments powered by Disqus

We like





We support


EFF - Electronic Frontier Foundation       TOR - The Onion Router       HRC - Human Rights Campaign