summaryrefslogtreecommitdiff
path: root/killchroot
blob: 2b71f6c614884b56a3c6e0058e5211a4c679c949 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/perl

my $sig = 15;
my $verbose = 0;
my $msg = '';
my $doit = 1;

while (@ARGV) {
  if ($ARGV[0] eq '-s' || $ARGV[0] eq '--signal') {
    die("$ARGV[0]: argument required") unless @ARGV > 1;
    $sig = $ARGV[1];
    shift @ARGV;
    shift @ARGV;
    next;
  }
  if ($ARGV[0] eq '-v' || $ARGV[0] eq '--verbose') {
    $verbose = 1;
    shift @ARGV;
    next;
  }
  if ($ARGV[0] eq '-n') {
    $doit = 0;
    $verbose = 1;
    shift @ARGV;
    next;
  }
  if ($ARGV[0] eq '-m' || $ARGV[0] eq '--message') {
    die("$ARGV[0]: argument required") unless @ARGV > 1;
    $msg = $ARGV[1];
    shift @ARGV;
    shift @ARGV;
    next;
  }
  last;
}

die("usage: killchroot [-s sig] <rootdir>") unless @ARGV == 1 && $ARGV[0] ne '';
my $dir = $ARGV[0];
chdir($dir) || die("$dir: $!\n");

$dir = readlink('/proc/self/cwd');
die("readlink /proc/self/cwd: $!\n") unless defined $dir;

my %pids;
my $pid;
my $path;

opendir(D, "/proc") || die("/proc: $!\n");
for $pid (readdir(D)) {
  next unless $pid =~ /^\d+$/;
  $path = readlink("/proc/$pid/root");
  next unless defined $path;
  if ($path =~ /^\Q$dir\E(\/.*)?$/) {
    $pids{$pid} = 1;
  }
  $path = readlink("/proc/$pid/exe");
  if ($path =~ /^\Q$dir\E(\/.*)?$/) {
    $pids{$pid} = 1;
  }
}
closedir(D);

my @pids = sort keys %pids;
exit 0 unless @pids;

print "$msg\n" if $msg ne '';

if ($verbose) {
  my @pidsv = ();
  for $pid (@pids) {
    open(F, "</proc/$pid/cmdline");
    my $cmd = '';
    sysread(F, $cmd, 128);
    close F;
    $cmd =~ s/\0.*//;
    #$cmd =~ s/ .*//;
    push @pidsv, "$pid($cmd)";
  }
  if (@pids > 1) {
    print "sending signal $sig to processes @pidsv\n";
  } else {
    print "sending signal $sig to process @pidsv\n";
  }
}
exit 0 unless $doit;
kill $sig => @pids;
kill CONT => @pids if $sig eq 9;
exit 0;