#!/bin/sh # 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: # debug() { if [ ${DEBUG:-0} -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 _who=$(whoami) [ -z "${_who}" ] && _who=$USER [ -z "${_who}" ] && _who=$LOGNAME [ -z "${_who}" ] && { echo "pidlock: Error: Neither whoami, \$USER nor \$LOGNAME returned a username!" 1>&2 exit 1 } PIDDIR=/tmp/${_who} /bin/mkdir -m 0700 -p ${PIDDIR} if [ "${?:-0}" -gt 0 ]; then echo "An error occured during mkdir of 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 echo "pstree -naup ${OLDPID}:" pstree -naup ${OLDPID} 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}