#!/bin/sh

###################################################################
# Copyright (c) 2023 Alex Kuryakin daqgroup@mail.ru
###################################################################
# It's utility to print defunct (Zombie) processes and his parents.
###################################################################
# https://askubuntu.com/questions/111422/how-to-find-zombie-process
###################################################################

function do_help(){
 echo "psdefunct version 1.0";
 if [ "$1" == "1" ]; then return; fi;
 echo "Copyright (c) 2023 Alex Kuryakin daqgroup@mail.ru";
 echo "psdefunct: utility to print defunct (Zombie) processes and his parents.";
};

function ps_zombie(){
 ps axo pid=,ppid=,stat=,cmd= | awk '$3~/^Z/ { print }';
};

function list_zombie_processes(){
 local list="$(ps_zombie | awk '{print $1}' | sort | uniq | tr '\n' ' ')";
 echo $list | tr ' ' ',';
};

function list_zombie_parents(){
 local list="$(ps_zombie | awk '{print $2}' | sort | uniq | tr '\n' ' ')";
 echo $list | tr ' ' ',';
};

#######
## MAIN
#######

function main(){
 case $1 in
  -h|-help|--help) do_help 0; return 0; ;;
  --version)       do_help 1; return 0; ;;
  *) ;;
 esac;
 local zombies="$(list_zombie_processes)";
 if [ -n "$zombies" ]; then
  echo "defunct Zombie processes: $zombies";
  ps_zombie;
  local parents="$(list_zombie_parents)";
  if [ -n "$parents" ]; then
   echo "defunct Zombie parents: $parents";
   ps o pid=,ppid=,stat=,cmd= -p $(list_zombie_parents);
  fi;
 fi;
};

main "$@";

##############
## END OF FILE
##############
