#!/usr/bin/env perl

# This kills the child processes of a process tree

use strict;

my (@f,$ln,$mypid,$parentprocess) = ();
my @subprocesses = ();
my $capture_begin = 0;


sub kill_children() {
	for (@_) {

		while( /\((.*?)\)/g ) {
			if($1 eq $mypid) {
				next;
			}
			printf "Killing PID %d\n",$1;
			`kill $1`;	
		}

	}
}

$parentprocess = shift;
if ( $parentprocess eq "") {
	print "Please specify name of parent process\n";
	exit 128;
}
# Most important line :-)

@f = `pstree -Apl | tr -s ' '`;

for $ln  ( @f ) {
	if( $ln =~ /^ \|-/) {
		last if ($capture_begin == 1);
		if($ln =~ /^ \|-$parentprocess\((.*?)\)/) {
			$capture_begin = 1;
			$mypid = $1;
			push(@subprocesses,"$ln"); 
		}
	}
	else {
		if( $capture_begin == 1) {
			push(@subprocesses,"$ln"); 
		}
	}
}
&kill_children(@subprocesses);


