Imported Upstream version 4.89
[platform/upstream/lsof.git] / scripts / count_pf.perl
1 #!/usr/local/bin/perl
2 #
3 # count_pf.perl-- run lsof in repeat mode and count processes and
4 #                 files
5
6 sub interrupt { print "\n"; exit 0; }
7
8 $RPT = 15;                              # lsof repeat time
9
10 # Set path to lsof.
11
12 if (($LSOF = &isexec("../lsof")) eq "") {       # Try .. first
13     if (($LSOF = &isexec("lsof")) eq "") {      # Then try . and $PATH
14         print "can't execute $LSOF\n"; exit 1
15     }
16 }
17
18 # Read lsof -nPF output repeatedly from a pipe.
19
20 $| = 1;                                 # unbuffer output
21 $SIG{'INT'} = 'interrupt';              # catch interrupt
22 $proc = $files = $proto{'TCP'} = $proto{'UDP'} = 0;
23 $progress="/";                          # used to show "progress"
24 open(P, "$LSOF -nPF -r $RPT|") || die "can't open pipe to $LSOF\n";
25
26 while (<P>) {
27     chop;
28     if (/^m/) {
29
30     # A marker line signals the end of an lsof repetition.
31
32         printf "%s  Processes: %5d,  Files: %6d,  TCP: %6d, UDP: %6d\r",
33             $progress, $proc, $files, $proto{'TCP'}, $proto{'UDP'};
34         $proc = $files = $proto{'TCP'} = $proto{'UDP'} = 0;
35         if ($progress eq "/") { $progress = "\\"; } else { $progress = "/"; }
36         next;
37     }
38     if (/^p/) { $proc++; next; }                # Count processes.
39     if (/^f/) { $files++; next; }               # Count files.
40     if (/^P(.*)/) { $proto{$1}++; next; }       # Count protocols.
41 }
42
43
44 ## isexec($path) -- is $path executable
45 #
46 # $path   = absolute or relative path to file to test for executabiity.
47 #           Paths that begin with neither '/' nor '.' that arent't found as
48 #           simple references are also tested with the path prefixes of the
49 #           PATH environment variable.  
50
51 sub
52 isexec {
53     my ($path) = @_;
54     my ($i, @P, $PATH);
55
56     $path =~ s/^\s+|\s+$//g;
57     if ($path eq "") { return(""); }
58     if (($path =~ m#^[\/\.]#)) {
59         if (-x $path) { return($path); }
60         return("");
61     }
62     $PATH = $ENV{PATH};
63     @P = split(":", $PATH);
64     for ($i = 0; $i <= $#P; $i++) {
65         if (-x "$P[$i]/$path") { return("$P[$i]/$path"); }
66     }
67     return("");
68 }