#!/usr/bin/perl
# $Id: oarkill,v 1.14 2005/04/04 13:11:55 capitn Exp $
# kill all childs of a pid
use strict;
use Data::Dumper;


if (!($ARGV[0] =~ /\d+/)){
    warn("Bad arguments for oarkill\n");
    exit(1);
}

# pid --> array of childs
my %processHash;
open(CMD, "ps -e -o pid,ppid |");
while (<CMD>){
    chomp($_);
    $_ =~ /(\d+)\s+(\d+)/;
    if (defined($1) && defined($2)){
        if (!defined($processHash{$2})){
            $processHash{$2} = [$1];
        }else{
            push(@{$processHash{$2}}, $1);
        }
    }
}

my @pidToKill;
my @potentialFather;
my $oneFather = $ARGV[0];
#search all pids to kill
while (defined($oneFather)){
       push(@pidToKill, $oneFather);
       #Get childs of this process
       foreach my $i (@{$processHash{$oneFather}}){
           push(@potentialFather, $i);
       }
       $oneFather = shift(@potentialFather);
}
#print(Dumper(@pidToKill));

#Kill all
while ($#pidToKill >= 0){
        my $pid = shift(@pidToKill);
        #print("sudo kill -9 $pid\n");
#        print("OAR is killing the job with pid=$pid\n");
        system("sudo /bin/kill -9 $pid 2>&1 > /dev/null");
}

exit(0);

