How to list only non- processes

processps

Is there a combination of command-line options for ps or pgrep or some other relatively direct way to determine if a particular process name is actually running (available for normal use)..

By "running", I mean to specifically exclude processes which are <defunct> or any other non-running processes (eg. zombies :)…

This sample script shows an example of <defunct> items:

#!/bin/bash   ubuntu 10.04

  pgrep ^gnuserv$
# 25591
# 25599
# 27330

  ps $(pgrep ^gnuserv$)  # command ammended as per pilcrow's good suggestion
#   PID TTY      STAT   TIME COMMAND
# 25591 ?        Zs     0:00 [gnuserv] <defunct>
# 25599 ?        Zs     0:00 [gnuserv] <defunct>
# 27330 pts/2    S+     0:00 gnuserv

I could further sed the output, but I think/hope there's a more direct way…

Best Answer

In your comment you clarify:

I'm actually looking for a single step option to ps or pgrep (or similar) which only outputs "active" processes...

I'm afraid you're out of luck with current ps/pgrep implementations.

Post filtering like this relies on a full understanding of the intial output, which I don't have...

But you can get that understanding and, better yet, control that output as desired. Try something like this:

function pgrep_live {
  pids=$(pgrep "$1");
  [ "$pids" ] || return;
  ps -o s= -o pid= $pids | sed -n 's/^[^ZT][[:space:]]\+//p';
}

That will return the pids for any pgrep'd processes matching your input string, which processes are "available for normal use," that is, neither dead+unreaped (Z) nor stopped (T).