File: top.rb

package info (click to toggle)
ruby-sys-proctable 1.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 396 kB
  • sloc: ruby: 3,656; makefile: 3
file content (37 lines) | stat: -rw-r--r-- 1,155 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
require 'sys/proctable'

# The Sys module serves as a namespace only
module Sys

  # The Top class serves as a toplevel name for the 'top' method.
  class Top

    # The version of the sys-top library
    VERSION = '1.0.5'.freeze

    # Returns an array of Struct::ProcTableStruct elements containing up
    # to +num+ elements, sorted by +field+. The default number of elements
    # is 10, while the default field is 'pctcpu'.
    #
    # Exception: the default sort field is 'pid' on AIX, Darwin and Windows.
    #
    def self.top(num = 10, field = 'pctcpu')
      field = field.to_s if field.is_a?(Symbol)

      aix = RbConfig::CONFIG['host_os'] =~ /aix/i
      darwin = RbConfig::CONFIG['host_os'] =~ /darwin/i
      dragonfly = RbConfig::CONFIG['host_os'] =~ /dragonfly/i

      # Sort by pid on Windows and AIX by default
      if (File::ALT_SEPARATOR || aix || darwin) && field == 'pctcpu'
        field = 'pid'
      end

      if dragonfly && field == 'pctcpu'
        Sys::ProcTable.ps.sort_by{ |obj| obj.lwp.pctcpu }[0..num-1]
      else
        Sys::ProcTable.ps.sort_by{ |obj| obj.send(field) || '' }[0..num-1]
      end
    end
  end
end