Skip to content

Instantly share code, notes, and snippets.



Created Jan 27, 2012
What would you like to do?
## dotkom kill,
## Roy Sindre Norangshol, <norangsh>
use Getopt::Std;
use strict;
use vars qw/ %opt /;
my $MAX_HOURS = 4;
sub init() {
getopts("hdDvn:e:", \%opt);
$MAX_HOURS = int($opt{n}) if ($opt{n} and int($opt{n})>0) ;
$opt{v} = 1 if $opt{d}; # enables verbose if dry-run.
usage() if ($opt{h} or (not $opt{d} and not $opt{v}) or not $opt{e});
sub KillOldProcesses() {
print "DRY-RUN , not killing anything ..\n" if $opt{d};
print "max-hours: $MAX_HOURS\n" if $opt{D};
print "expression: $opt{e}\n" if $opt{D};
my $any_hits = undef;
open(PS, "ps -eo '%U\t%p\t%t\t%a' --sort user |") || die "Failed: $!\n";
while (<PS>) {
my ($user,$pid,$elapsed,$args) = split(/\t/);
if ($args=~/$opt{e}/ && $elapsed =~/(\d{0,9})-(\d{1,2}):\d{1,2}:\d{1,2}/) {
if ($2) {
my($hours) = int($2);
if ($1) {
$hours = (int($1)*24)+$hours; ## add days*24hours to elapsed hours
if ($hours>=$MAX_HOURS) {
if (not $any_hits) {
print "Killing processes older then $MAX_HOURS hours by expression: $opt{e}\n\n" if $opt{v};
$any_hits = 1;
print "Killing(SIGTERM) $user, pid $pid running $hours hours\t: $args" if $opt{v};
system("kill $pid") if not $opt{d};
sub usage() {
print STDERR << "EOF";
This program lets you kill processes if they are older then "\$MAX_HOURS" hours
usage: $0 [-hdve] EXPRESSION to match against commandname with arguments in ps
-h : this (help) message
-v : verbose output
-d : dry run, will enable verbose and not execute the kills
-D : debug (more verbose output)
-n : kill processes older then #n hours , defaults to 4 hours.
example: $0 -ve python
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.