#!/bin/sh # # Background a command. # Copy output to a log. # Record the pid in a file. # NoHUP it. # - Cameron Simpson 25aug1999 # : ${LOGDIR:=$HOME/var/log} : ${CONSOLE:=$LOGDIR/console} : ${VARRUN:=$HOME/var/run} cmd=`basename "$0"` input=/dev/null logfile=$CONSOLE pidfile= ignhup=1 async=1 usage="Usage: $cmd [-i input] [-l logfile] [-p pidfile] [-s] command [args...] -i input Input path. \"-\" means don't change stdin. Default: $input -l logfile Output and error output path. \"-\" means don't change stdout or stderr. Default, from \$CONSOLE: $logfile -p pidfile File to hold process id. \"-\" means write the pid to stdout. \"\" means write the pid file to \$VARRUN/command@\$HOST -s Synchronous - wait for the process to terminate. Default: asynchronous." badopts= while : do case $1 in -i) input=$2; shift ;; -l) logfile=$2; shift ;; -p) pidfile=$2; shift ;; -s) async= ;; --) shift; break ;; -?*) echo "$cmd: unrecognised option: $1" >&2 badopts=1 ;; *) break ;; esac shift done if [ $# = 0 ] then echo "$cmd: missing command" >&2 badopts=1 fi [ $badopts ] && { echo "$usage" >&2; exit 2; } command=$1 combase=`basename "$command"` [ -n "$logfile" ] || logfile=$combase@$HOST [ -n "$pidfile" ] || pidfile=$combase@$HOST case $logfile in -|/*) ;; *) logfile=$LOGDIR/$logfile ;; esac case $pidfile in -|/*) ;; *) pidfile=$VARRUN/$pidfile ;; esac ## echo "logfile=$logfile, pidfile=$pidfile" exec 9<&0 ( if [ "x$input" = x- ] then exec <&9 else exec <"$input" fi exec 9<&- [ "x$logfile" = x- ] || exec >>"$logfile" 2>&1 [ $ignhup ] && trap '' 1 [ $async ] && trap '' 2 exec "$@" ) & pid=$! # close input just in case exec <&- ( [ "x$pidfile" = x- ] || exec >"$pidfile" echo "$pid" ) [ $async ] || wait