Created
June 19, 2020 04:04
-
-
Save kazuho/0178ebbf83a103ed99813a998876fd69 to your computer and use it in GitHub Desktop.
script for collecting CPU and network usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/perl | |
use strict; | |
use warnings; | |
use Getopt::Long; | |
use Scope::Guard; | |
my $nic; | |
GetOptions("nic=s" => \$nic); | |
if (@ARGV == 0) { | |
print "Usage: $0 <cmd ...>\n"; | |
exit 0; | |
} | |
$SIG{INT} = sub {}; | |
my @stats_start = read_stat(); | |
my $pid = fork; | |
die "fork failed: $!" | |
unless defined $pid; | |
if ($pid == 0) { | |
# child process | |
exec @ARGV; | |
die "failed to exec $ARGV[0]:$!"; | |
} | |
while (wait() != $pid) {} | |
my @stats_stop = read_stat(); | |
my @fields = qw(user nice sys idle iowait hardirq softirq rxpackets rxbytes txpackets txbytes); | |
for (my $i = 0; $i < @fields; ++$i) { | |
print " " if $i != 0; | |
print "$fields[$i] @{[$stats_stop[$i] - $stats_start[$i]]}" | |
if defined $stats_start[$i]; | |
} | |
print "\n"; | |
sub read_stat { | |
my @v; | |
open my $fh, "<", "/proc/stat" | |
or die "failed to open /proc/stat:$!"; | |
while (my $line = <$fh>) { | |
if ($line =~ /^cpu\s+/) { | |
@v = split /\s+/, $'; | |
last; | |
} | |
} | |
die "could not find line starting with `cpu ` in /proc/stat" | |
unless @v; | |
close $fh; | |
if ($nic) { | |
open my $fh, '-|', 'ifconfig', $nic | |
or die "failed to invoke ifconfig $nic:$!"; | |
while (my $line = <$fh>) { | |
if ($line =~ /RX packets (\d+)\s+bytes (\d+)/) { | |
$v[7] = $1; | |
$v[8] = $2; | |
} elsif ($line =~ /TX packets (\d+)\s+bytes (\d+)/) { | |
$v[9] = $1; | |
$v[10] = $2; | |
} | |
} | |
close $fh; | |
} | |
@v; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment