Jason
Jason

Reputation: 1069

Portable shell solution to check if PID is zombied

I want to check if a PID is running (that is, exists and is not zombied).

It's really quick to do from /proc/$PID/stat but I'd like something more portable.

The best I have right now is:

( STAT="$(ps -ostat= -p$PID)"; test "$STAT" -a "$STAT" "!=" "Z" )

Which seems to work on BSD and Linux. Is there a better way?

Upvotes: 25

Views: 610

Answers (2)

hairy yuppie
hairy yuppie

Reputation: 321

Hopefully POSIX compliant. Tested with dash. To use it, save it with your favorite editor, make it executable (chmod 755 foo.sh), and run it with a PID argument.

Of course you can adapt it as needed.

#!/bin/sh
pid="$1";
psout=$(ps -o s= -p "$pid");
pattern='[SRDTWX]';

case "$psout" in 
    $pattern) echo "Not a zombie";;
    Z) echo "Zombie found";;
    *) echo "Incorrect input";; 
esac

Upvotes: 1

Bastian Bittorf
Bastian Bittorf

Reputation: 507

IMHO parsing the output of 'ps' is the most portable way. all the 'ps' variant out there differ a little bit in the syntax, but the overall output is good enough:

#!/bin/sh

process_show()
{
  ps
  ps ax
}

pid_is_zombie()
{
  pid="$1"

  process_show | while read -r LINE; do
    # e.g.: 31446 pts/7    R+     0:00 ps ax
    set -f
    set +f -- $LINE

    test "$1" = "$pid" || continue
    case "$3" in *'Z'*) return 0;; esac
  done

  return 1
}

pid_is_zombie 123 && echo "yes it is"

even 'ps ax' is not possible everywhere, so we must try 'ps' and 'ps ax'.

Upvotes: 0

Related Questions