pidofproc function in functions script

Dennis J Perkins dennisjperkins at comcast.net
Wed Jul 4 21:31:46 PDT 2007


I played with pidofproc and this seems to work properly.  I don't know
if it would integrate into your functions without any changes.

I don't tend to put variables between braces unless necessary.  I
haven't decided if I like that behavior, but it does have the virtue of
being consistent.

I used getopts instead of your while loop.  I discovered that t does not
detect options after a parameter.

I also included an exit code for a syntax error, but LSB doesn't call
for it.  Since pidofproc is meant to be called by other functions, it
might not be that useful anyway.

It also returns a list of found pids.  LSB specifies exit codes but is
silent on return vaues.


# Function:    pidofproc [-p pidfile] pathname
#
# Description: Search for pids of process.  If -p option is used,
#              pidfile is used instead of looking for pid in /var/run.
#
# Options:    -p pidfile   - Use pidfile instead of pidfile
#                            in /var/run.
#
# Parameters:  pathname    - complete pathname of program
#
# Returns:     list of found pids
#
# Exit code    0 - Processs found.
#              1 - Process is not running but pidfile still exists
#                  in /var/run.
#              2 - Syntax error.
#              3 - Process is not running.

pidofproc()
{
    local base    # basename of program
    local opt     # option currently being processed
    local pid     # pid from pidfile
    local pids    # list of pids to return to calling function
    local pidfile # pidfile passed to pidofproc
    local pidlist # list of pids to be returned to calling function
    local process # 

    local usage="Usage: pidofproc [-p pidfile] program"

    while getopts ":p:" opt
    do
        case $opt in
	    p ) pidfile=$OPTARG ;;
	    * ) log_error_msg $usage
	        exit 2 ;;  # Syntax error
        esac
    done
    shift $((OPTIND - 1 ))

    # Check argument count.
    if [ $# -ne 1 ]; then
        log_error_msg $usage
        return 2   # Syntax error
    fi

    # Name of process that we want pid for.
    process=$1

    # If a pidfile was not passed, look for one in /var/run.
    base=${process##*/}
    ${pidfile:=/var/run/$base.pid} 2> /dev/null

    if [ -f "$pidfile" ]; then
        # LSB specifies that only the first line of the pidfile should
be read.
        read pidlist < $pidfile
    else
        # No pidfile.  Try to find pid anyway.
        pidlist=$(pidof -s $$ -o $PPID -x $process)
	if [ -z "$pidlist" ]; then
	    return 3  # Not running
        fi
    fi
-
    # Build list of pids of running processes.
    for pid in "$pidlist"
    do
        if kill -0 "$pid" 2> /dev/null ; then
            pids="$pids $pid"
        fi
    done

    if [ -z "$pids" ]; then
        return 1  # Not running, but pid found.
    else
        echo $pids
    fi
}





More information about the lfs-support mailing list