Tag Archives: process

Grep and Kill process on linux. Kill process in linux matching a string / Grep

nuke – Named keeping in mind that it could kill process with matches all the process given by a string. This is a perl program with take input a  string which you are trying to grep and kill.

 


#!/usr/bin/perl

 

use strict;
use Term::ANSIColor qw(:constants);
use Shell;

my (@procs, @all, @pid_list, @proc_name);
sub ps;

die ("Usage: kill.pl <string_to_match>\n") if (scalar(@ARGV) == 0);

@all = ps('-ef');

my $str = $ARGV[0];
my @procz = grep (/$str/, @all);

foreach (@procz){
if(/vim/ or /emacs/ or /xterm/){
next;
}
push(@procs, $_);
}
@pid_list = map {(split( /\s+/, $_))[1]} @procs;

@proc_name = ();

foreach(@procs){
my (@a, $b, @c);
@c = ();
@a = split(/\s/, $_);
foreach $b (@a){
chomp($b);
next if length($b) == 0;
@c = (@c, $b);
}
@proc_name = (@proc_name, $c[7]);
}
if(scalar(@procs) > 1){
printf("%-10s %-65s %-15s\n", "PID", "PROCESS", "STATUS");
printf("%-10s %-65s %-15s\n\n", "-" x 10, "-" x 65, "-" x 15);
}

for(my $i = 0; $i < scalar(@pid_list); $i++){
chomp($pid_list[$i]);
if(!defined($pid_list[$i]) or (length("$pid_list[$i]") == 0) or $pid_list[$i] == $$){

print (RESET);
next;
}
chomp($proc_name[$i]);
my $pname = $proc_name[$i];
my $pidx = -1;

$pidx = rindex($pname, "/");
if($pidx > 0){
$pidx -= 1;
foreach (0..4){
$pidx = rindex($pname, "/", $pidx);
last if ($pidx == -1);
$pidx -= 1;
}
if($pidx > 0){
$pidx += 1;
$pname = substr($pname, $pidx);
$pname = "...$pname";
$proc_name[$i] = $pname;
}
}

print(YELLOW);
printf("%-10s %-65s ", $pid_list[$i], $proc_name[$i]);
my $count = kill ("KILL", $pid_list[$i]);
if($count == 1){
print(RED);
printf ("%-15s\n", "[ KILLED ]");
}
else{
print(BLUE);
printf ("%-15s\n", "[ ALIVE ]");
}
print(RESET);
}
if(scalar(@procs) > 1){
printf("%-10s %-65s %-15s\n", "-" x 10, "-" x 65, "-" x 15);
}