chordStats.pl 程序
一般策略
节拍、音色、和音以及通知速率的选择综合了艺术与科学两个方面,而这种综合的方式已经远远超出本文讨论范围。为了简化开发及信息分发,此程序的主要特性包括 1-Hz 刷新率和基于八度音阶的通知标准。vmstat 程序为基本系统数据提供了一个简单接口,而且创建了一个 1-Hz “心跳” 并以它为节拍。
清单 2. 主程序参数
#!/usr/bin/perl -w # chordStats.pl - create music based on system status use strict; my $vmStatCmd = "vmstat 1"; # run vmstat every second my $totalPackets = 0; # total of packets received and transmitted my $lineCount = 0; # count number of vmstat output lines my %fields = (); my $count = 0; # the field headers in the vmstat output, useful for referring to them by name for( split " ", "r b swpd free buff cache si so bi bo in cs us sy id wa" ){ $fields{$_} = $count; $count++; } # buffering output must be turned off because fluidsynth does not appear to # accept buffered input from stdin $|=1; |
在脚本的开头,我们选择 vmstat 1 作为要被执行的命令并且每秒读取一次。为各次读取之间记录的信息包总数设置一个变量并记录从 vmstat 程序中读取到的行数,接下来定义标题。每秒都会从 vmstat 程序中读取字段标题 bi(磁盘块入)、bo(磁盘块出)和 us(用户 CPU 使用量)。字段散列允许稍后在程序中按名称引用这些数据字段。请注意 $|=1 行。如果删除此行,您将会遇到一些难以诊断的行为;还需要为缓冲而头疼!
清单 3. 主程序开始
# open the vmstat program to read from open( INPIPE, "$vmStatCmd |" ) || die "can't read from vmstat"; # wait while the fluidsynth program opens sleep(3); while(my $statLine = <INPIPE> ){ # ignore the header display, and the fieldname display lines if( $statLine !~ /\-\-\-\-/ && $statLine !~ /swpd/ ){ # the first line of vmstat data is a recent average, ignore if( $lineCount > 2 ){ |
代码的下一部分将通过 vmstat 命令创建一个管道,程序将在其中每秒读取一次数据。等待几秒待 FluidSynth 程序激活后,即可开始处理 vmstat 输出。输出的前三行将被忽略,因为它们分别包含分隔符、标题信息和最新的平均值。
清单 4. 主程序通知处理
# reset wavetable synthesis if( $totalTime % 10 == 0 ){ print "reset\n" } $totalTime ++; my $note = ""; my @currLine = split " ", $statLine; # user cpu usage $note = $currLine[ $fields{us} ]; sendNote( $note, 14, 12, 96 ); # conglomerate disk i/o fields to one stat $note = $currLine[ $fields{bi} ] + $currLine[ $fields{bo} ]; if( $note > 1000 ){ $note = 1000; } $note = $note/10; sendNote( $note, 8, 12, 96 ); # network throughput on eth0 $note = getNetworkStats(); sendNote( $note, 5, 12, 84 ); }#if not first 3 lines to ignore }#if not a header line $lineCount++; }#while reading the pipe close(INPIPE); |