@@ -137,25 +137,40 @@ def self.capture_memory(processes)
137137 #
138138 # @parameter pid [Integer] The process ID to capture.
139139 # @parameter ppid [Integer] The parent process ID to capture.
140- def self . capture ( pid : nil , ppid : nil , ps : PS , memory : Memory . supported? )
141- input , output = IO . pipe
140+ def self . capture ( pid : nil , ppid : nil , memory : Memory . supported? )
141+ ps_pid = nil
142142
143- arguments = [ ps ]
144-
145- if pid && ppid . nil?
146- arguments . push ( "-p" , Array ( pid ) . join ( "," ) )
147- else
148- arguments . push ( "ax" )
143+ # Extract the information from the `ps` command:
144+ header , *lines = IO . pipe do |input , output |
145+ arguments = [ PS ]
146+
147+ if pid && ppid . nil?
148+ arguments . push ( "-p" , Array ( pid ) . join ( "," ) )
149+ else
150+ arguments . push ( "ax" )
151+ end
152+
153+ arguments . push ( "-o" , FIELDS . keys . join ( "," ) )
154+
155+ ps_pid = Process . spawn ( *arguments , out : output )
156+ output . close
157+
158+ input . readlines . map ( &:strip )
159+ ensure
160+ input . close
161+
162+ if ps_pid
163+ begin
164+ # Make sure to kill the ps process if it's still running:
165+ Process . kill ( :KILL , ps_pid )
166+ # Reap the process:
167+ Process . wait ( ps_pid )
168+ rescue => error
169+ warn "Failed to cleanup ps process #{ ps_pid } :\n #{ error . full_message } "
170+ end
171+ end
149172 end
150173
151- arguments . push ( "-o" , FIELDS . keys . join ( "," ) )
152-
153- ps_pid = Process . spawn ( *arguments , out : output )
154-
155- output . close
156-
157- header , *lines = input . readlines . map ( &:strip )
158-
159174 processes = { }
160175
161176 lines . map do |line |
@@ -187,17 +202,6 @@ def self.capture(pid: nil, ppid: nil, ps: PS, memory: Memory.supported?)
187202 end
188203
189204 return processes
190- ensure
191- if ps_pid
192- begin
193- # Make sure to kill the ps process if it's still running:
194- Process . kill ( :KILL , ps_pid )
195- # Reap the process:
196- Process . wait ( ps_pid )
197- rescue => error
198- warn "Failed to cleanup ps process #{ ps_pid } :\n #{ error . full_message } "
199- end
200- end
201205 end
202206 end
203207 end
0 commit comments