Associative Arrays
SystemTap also supports the use of associative arrays. While an ordinary variable represents a single value, associative arrays can represent a list of values arranged in tabular format. Simply put, an associative array is a collection of unique keys; each key in the array has a value associated with it. Illustrating this visually would be similar to creating a two-column table: the first column would have the unique key, while the second column would have the associated value.
Associative arrays are useful in processing data that would normally be represented best in tabular format. For example, let's say you wanted to see how many times any specific program performs a read to the virtual file system. In this case, your probe would use the event kernel.function("vfs_read"); execname() identifies which program or process performs the read.
vfsreads.stp
probe kernel.function("vfs_read")
{
printf("%s\n", execname())
}
will display the name of each program that performs a read to the virtual file system as each read is performed. This means that the output of will be a long list of process names, most of which will be repeating. For to be useful, you'd need to feed its output to another program that counts how many times each process name appears and tally the results.
However, with the help of arrays, you can simplify the task using the following script:
vfsreads-using-arrays.stp
global reads
probe kernel.function("vfs_read")
{
reads[execname()] += $count
}
probe timer.s(2)
{
foreach (key in reads)
printf("%s : %d\n", key, reads[key])
exit()
}
The handler in the first probe of does three things:
First, the handler defines the variable reads as the associative array.
Next, the handler uses execname() (the names of the processes that execute the VFS reads) as the array's unique keys. For example, once the process gnome-terminal performs a VFS read, the array creates a unique key named gnome-terminal, which has an initial associated value of 1.
Finally, the statement += $count increments the value associated with each unique key every time that unique key "occurs"; for example, each time that the process gnome-terminal performs a VFS read, the value associated with the unique key gnome-terminal gets incremented by 1.
Note
In , $count is not a variable; rather, it is an operation that instructs the array to perform an increment to the array. This book will discuss other similar operations in detail later.
TBD WILL ADD MORE INFO ON ARRAY SYNTAX IN A SUBSEQUENT SECTION, FIX PREVIOUS NOTE TO XREF TO SECTION ONCE ITS BUILT
The handler in the second probe of prints the script's output o the format name : value over the span of two seconds, then exits. name is the process that executed a VFS read, and value is how many times name executed a VFS read). For example:
Sample Output for
gnome-terminal : 64
gnome-screensav : 128
gnome-power-man : 512
pcscd : 534
cupsd : 1023
mixer_applet2 : 1440
gnome-vfs-daemo : 2048
snmpd : 2048