Class: Appear::Processes

Inherits:
Service show all
Defined in:
lib/appear/processes.rb

Overview

The Processes service handles looking up information about a system process. It mostly interacts with the ‘ps` system utility.

Defined Under Namespace

Classes: ProcessInfo

Instance Method Summary collapse

Methods inherited from BaseService

delegate, require_service, required_services

Constructor Details

#initialize(*args) ⇒ Processes

Returns a new instance of Processes.



26
27
28
29
# File 'lib/appear/processes.rb', line 26

def initialize(*args)
  super(*args)
  @get_info_memo = Util::Memoizer.new
end

Instance Method Details

#alive?(pid) ⇒ Boolean

Is the given process alive?

Parameters:

  • pid (Integer)

Returns:

  • (Boolean)


45
46
47
48
49
50
51
52
# File 'lib/appear/processes.rb', line 45

def alive?(pid)
  begin
    ::Process.getpgid(pid)
    true
  rescue Errno::ESRCH
    false
  end
end

#get_info(pid) ⇒ ProcessInfo

Get info about a process by PID, including its command and parent_pid.

Parameters:

  • pid (Integer)

Returns:



35
36
37
38
39
# File 'lib/appear/processes.rb', line 35

def get_info(pid)
  @get_info_memo.call(pid) do
    fetch_info(pid)
  end
end

#pgrep(pattern) ⇒ Array<Integer>

Returns pids found.

Parameters:

  • pattern (String)

Returns:

  • (Array<Integer>)

    pids found



67
68
69
70
71
72
73
74
# File 'lib/appear/processes.rb', line 67

def pgrep(pattern)
  output = run(['pgrep', '-lf', pattern])
  output.lines.map do |line|
    line.strip.split(/\s+/).first.to_i
  end
rescue Appear::ExecutionFailure
  []
end

#process_tree(pid) ⇒ Array<ProcessInfo>

look up all the processes between the given pid and PID 1

Parameters:

  • pid (Number)

Returns:



57
58
59
60
61
62
63
# File 'lib/appear/processes.rb', line 57

def process_tree(pid)
  tree = [ get_info(pid) ]
  while tree.last.pid > 1 && tree.last.parent_pid != 0
    tree << get_info(tree.last.parent_pid)
  end
  tree
end