Update uid/gid of build root if uid/gid is not match
[tools/obs-build.git] / killchroot
1 #!/usr/bin/perl
2
3 my $sig = 15;
4 my $verbose = 0;
5 my $msg = '';
6 my $doit = 1;
7
8 while (@ARGV) {
9   if ($ARGV[0] eq '-s' || $ARGV[0] eq '--signal') {
10     die("$ARGV[0]: argument required") unless @ARGV > 1;
11     $sig = $ARGV[1];
12     shift @ARGV;
13     shift @ARGV;
14     next;
15   }
16   if ($ARGV[0] eq '-v' || $ARGV[0] eq '--verbose') {
17     $verbose = 1;
18     shift @ARGV;
19     next;
20   }
21   if ($ARGV[0] eq '-n') {
22     $doit = 0;
23     $verbose = 1;
24     shift @ARGV;
25     next;
26   }
27   if ($ARGV[0] eq '-m' || $ARGV[0] eq '--message') {
28     die("$ARGV[0]: argument required") unless @ARGV > 1;
29     $msg = $ARGV[1];
30     shift @ARGV;
31     shift @ARGV;
32     next;
33   }
34   last;
35 }
36
37 die("usage: killchroot [-s sig] <rootdir>") unless @ARGV == 1 && $ARGV[0] ne '';
38 my $dir = $ARGV[0];
39 chdir($dir) || die("$dir: $!\n");
40
41 $dir = readlink('/proc/self/cwd');
42 die("readlink /proc/self/cwd: $!\n") unless defined $dir;
43
44 my %pids;
45 my $pid;
46 my $path;
47
48 opendir(D, "/proc") || die("/proc: $!\n");
49 for $pid (readdir(D)) {
50   next unless $pid =~ /^\d+$/;
51   $path = readlink("/proc/$pid/root");
52   next unless defined $path;
53   if ($path =~ /^\Q$dir\E(\/.*)?$/) {
54     $pids{$pid} = 1;
55   }
56   $path = readlink("/proc/$pid/exe");
57   if ($path =~ /^\Q$dir\E(\/.*)?$/) {
58     $pids{$pid} = 1;
59   }
60 }
61 closedir(D);
62
63 my @pids = sort keys %pids;
64 exit 0 unless @pids;
65
66 print "$msg\n" if $msg ne '';
67
68 if ($verbose) {
69   my @pidsv = ();
70   for $pid (@pids) {
71     open(F, "</proc/$pid/cmdline");
72     my $cmd = '';
73     sysread(F, $cmd, 128);
74     close F;
75     $cmd =~ s/\0.*//;
76     #$cmd =~ s/ .*//;
77     push @pidsv, "$pid($cmd)";
78   }
79   if (@pids > 1) {
80     print "sending signal $sig to processes @pidsv\n";
81   } else {
82     print "sending signal $sig to process @pidsv\n";
83   }
84 }
85 exit 0 unless $doit;
86 kill $sig => @pids;
87 kill CONT => @pids if $sig eq 9;
88 exit 0;