Class: Pipes::SingleCommandPipe

Inherits:
Object
  • Object
show all
Defined in:
lib/single_command_pipe.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#command_pidObject (readonly)

Returns the value of attribute command_pid.



4
5
6
# File 'lib/single_command_pipe.rb', line 4

def command_pid
  @command_pid
end

Instance Method Details

#child_pids(parent_pid) ⇒ Object



46
47
48
# File 'lib/single_command_pipe.rb', line 46

def child_pids(parent_pid)
  pgrep_parent_pid(parent_pid).split.map(&:to_i)
end

#kill_current_process_treeObject



35
36
37
# File 'lib/single_command_pipe.rb', line 35

def kill_current_process_tree
  kill_process_tree command_pid if command_pid
end

#kill_procObject



31
32
33
# File 'lib/single_command_pipe.rb', line 31

def kill_proc
  proc { kill_current_process_tree }
end

#kill_proc_with_previous(previous_proc) ⇒ Object



27
28
29
# File 'lib/single_command_pipe.rb', line 27

def kill_proc_with_previous(previous_proc)
  proc { kill_current_process_tree; previous_proc.call }
end

#kill_process_tree(starting_pid) ⇒ Object



39
40
41
42
43
44
# File 'lib/single_command_pipe.rb', line 39

def kill_process_tree(starting_pid)
  child_pids(starting_pid).each do |child_pid|
    kill_process_tree(child_pid)
  end
  Process.kill("TERM", starting_pid) rescue nil
end

#pgrep_parent_pid(parent_pid) ⇒ Object



50
51
52
# File 'lib/single_command_pipe.rb', line 50

def pgrep_parent_pid(parent_pid)
  `pgrep -P #{parent_pid}`
end

#put_synchronously(command) ⇒ Object



6
7
8
9
10
11
12
13
14
# File 'lib/single_command_pipe.rb', line 6

def put_synchronously(command)
  setup_trap

  @pipe = IO.popen(command)
  @command_pid = @pipe.pid
  output = @pipe.readlines
  @command_pid = nil
  output
end

#setup_trapObject



16
17
18
19
20
21
22
23
24
25
# File 'lib/single_command_pipe.rb', line 16

def setup_trap
  previous_term_trap = trap("TERM",kill_proc)
  if previous_term_trap != "DEFAULT"
    trap("TERM", kill_proc_with_previous(previous_term_trap))
  end

  #if previous_exit_trap = trap("EXIT", kill_proc)
  #  trap("EXIT", kill_proc_with_previous(previous_exit_trap))
  #end
end