#!/bin/bash # distributed by cfengine # Copyright 1999-2010 Gentoo Foundation # Distributed under the beerware license # Author: Robin H. Johnson # Servers: stork # Path on server: /usr/local/bin/ # Permissions: -rwxr-xr-x root root # Comments: # function debug() { if [[ $DEBUG -eq 1 ]]; then echo "DEBUG: pidlock: ${*}" fi } while getopts ":l:s:d" opt; do case $opt in l) PIDDIR=$OPTARG ;; s) MYSUFFIX=$OPTARG ;; d) DEBUG=1 ;; :) echo "Option '-${OPTARG}' requires an argument." 1>&2 exit 1 ;; \?) echo "Usage: ${0}: [-l PIDDIR] [-s PIDFILE_SUFFIX] [-d] -- args" exit 0 ;; *) continue ;; esac done shift $(($OPTIND - 1)) if [[ -z "${PIDDIR}" ]]; then if [ -z "${USER}" ]; then if [ -n "${LOGNAME}" ]; then USER="${LOGNAME}" else echo "\$USER is not set!" 1>&2 exit 2 fi fi PIDDIR=/tmp/${USER} /bin/mkdir -p ${PIDDIR} ERR=$? /bin/chmod 700 ${PIDDIR} ERR=$((${ERR}+$?)) if [ "${ERR}" -gt 0 ]; then echo "Some error in creating the PIDDIR!" 1>&2 exit 3 fi fi if [[ ! -d "${PIDDIR}" ]]; then echo "Error: '${PIDDIR}' does not exist!" 1>&2 exit 3 fi if [ -z "${1}" ]; then echo "Error! You need to specify a command to run!" 1>&2 exit 1 fi MYPID=$$ MYNAME=`/bin/basename $0`-`/bin/basename $1` CMD="${*}" if [[ -n "${MYSUFFIX}" ]]; then PIDFILE=${PIDDIR}/${MYNAME}-${MYSUFFIX}.pid else PIDFILE=${PIDDIR}/${MYNAME}.pid fi if [ -f "${PIDFILE}" ]; then OLDPID=$(< ${PIDFILE}) if [[ -d "/proc/${OLDPID}/" ]]; then OLDCMD=$(/usr/bin/tr '\000' ' ' < /proc/${OLDPID}/cmdline | /bin/grep -o "${0} ${CMD}") if [[ -n "${OLDCMD}" ]]; then echo "Error! '${MYNAME}' is running already!" 1>&2 exit 4 else echo "Error: A running process with the pid '${OLDPID}' taken from '${PIDFILE}' has been found!" 1>&2 exit 4 fi fi debug "Stale pidfile detected. Removing" /bin/rm -f ${PIDFILE} fi debug "Not running already, putting PID in pidfile" echo ${MYPID} >${PIDFILE} debug "Doing something (${CMD})" eval ${CMD} debug "Cleaning up ${PIDFILE}" /bin/rm -f ${PIDFILE}