1#
2# Kill all instances of a process by pattern-matching the command-line
3#
4# (c) 2000 by Aaron Sherman, see documentation, below for details.
5
6package Proc::Killall;
7
8require Exporter;
9use Carp;
10use Proc::ProcessTable;
11use Config;
12use strict;
13use warnings;
14use vars qw(@EXPORT @EXPORT_OK @ISA $VERSION);
15
16@EXPORT=qw(killall);
17@EXPORT_OK=qw(killall);
18@ISA=qw(Exporter);
19
20$VERSION='1.0';
21
22# Private function for checking to see if a signal identifier is
23# valid.
24sub is_sig {
25	my $sig = shift;
26	if (defined($sig)) {
27		if ($sig =~ /^-?(\d+)/) {
28			my $n = $1;
29			my @sigs = split ' ', $Config{sig_num};
30			return grep {$_ == $n} @sigs;
31		} elsif ($sig =~ /^[A-Z][A-Z0-9]+$/) {
32			my @sigs = split ' ', $Config{sig_name};
33			return grep {$_ eq $sig} @sigs;
34		} else {
35			return 0;
36		}
37	} else {
38		return 0;
39	}
40}
41
42# usage: killall(signal, pattern)
43# return: number of procs killed
44sub killall {
45	croak("Usage: killall(signal, pattern)") unless @_==2;
46	my $signal = shift;
47	my $pat = shift;
48	my $self = shift;
49	$self = 0 unless defined $self;
50	my $nkilled = 0;
51	croak("killall: Unsupported signal: $signal") unless is_sig($signal);
52	my $t = Proc::ProcessTable->new;
53	my $BANG = undef;
54	foreach my $p (@{$t->table}) {
55	  my $cmndline = $p->{cmndline} || $p->{fname};
56	  if ($cmndline =~ /$pat/) {
57			next unless $p->pid != $$ || $self;
58			if (kill $signal, $p->pid) {
59				$nkilled++;
60			} else {
61				$BANG = $!;
62			}
63		}
64	}
65	$! = $BANG if defined $BANG;
66	return $nkilled;
67}
68
691;
70
71__END__
72
73=head1 NAME
74
75killall - Kill all instances of a process by pattern matching the command-line
76
77=head1 SYNOPSIS
78
79	use Proc::Killall;
80
81	killall('HUP', 'xterm'); # SIGHUP all xterms
82	killall('KILL', '^netscape$'); # SIGKILL to "netscape"
83
84=head1 DESCRIPTION
85
86This module provides one function, C<killall()>, which takes two parameters:
87a signal name or number (see C<kill()>) and a process pattern. This pattern
88is matched against the process' command-line as the C<ps> command would
89show it (C<ps> is not used internally, instead a package called
90C<Proc::ProcessTable> is used).
91
92C<killall> searches the process table and sends that signal to all processes
93which match the pattern. The return value is the number of processes that
94were successfully signaled. If any kills failed, the C<$!> variable
95will be set based on that last one that failed (even if a successful kill
96happened afterward).
97
98=head1 AUTHOR
99
100Written in 2000 by Aaron Sherman E<lt>ajs@ajs.comE<gt>
101
102C<Proc::Killall> is copyright 2000 by Aaron Sherman, and may be
103distributed under the same terms as Perl itself.
104
105=head1 PREREQUISITES
106
107C<Proc::ProcessTable> is required for C<Proc::Killall> to function.
108
109=head1 SEE ALSO
110
111L<perl>, L<perlfunc>, L<perlvar>, L<Proc::ProcessTable>
112