return to first page linux journal archive
keywordscontents

Listing 1.

local lasttimes, timerid

on updatelist
  local procstat, newtotaltime, totaltime, procs, procid, procpath
  local newtime, percenttime, toplist

# let the user know we're working
  set the cursor to watch
  put readfile("/proc/stat") into procstat
# compute total user, system, and idle time
  put word 2 of procstat + word 3 of procstat + word 4 of procstat\
        + word 5 of procstat into newtotaltime
# the first time through, totaltime will be 0, so prevent divide by 0
  put max(1, newtotaltime - lasttimes["total"]) into totaltime
  put newtotaltime into lasttimes["total"]
# get a list of directories along with the owner of each
  put shell("ls -l /proc") into procs
  delete line 1 of procs # delete "total" line
  repeat for each line l in procs
    put the last word of l into procid
    if procid is not a number then next repeat
# build up path by concatenating id and a trailing "/"
    put "/proc/" & procid & "/" into procpath
    put readfile(procpath & "stat") into procstat
    if procstat is empty then next repeat # no file
    put word 14 of procstat + word 15 of procstat into newtime
    put (newtime - lasttimes[procid]) / totaltime * 100 into percenttime
# store time into associative array by proc id
    put newtime into lasttimes[procid]
# format one line of output using format function (like C printf function)
    put format("%5s %-10s %5d %5d %4d %s\n", word 1 of procstat, word 3 of l,\
          word 23 of procstat div 1024, word 24 of procstat * 4, percenttime,\
          readfile(procpath & "cmdline")) after toplist
  end repeat
  delete last char of toplist # get rid of trailing newline
# double sort sorts by process size and then by CPU usage
  sort lines of toplist numeric by word 4 of each
  sort lines of toplist descending numeric by word 5 of each
  put toplist into field "toplist"
# set up a call back in a few seconds
  send "updatelist" to me in (the updateinterval of me) seconds
  put the result into timerid
  disable button "Kill Process"
  set the cursor to hand
end updatelist