Last active
August 28, 2020 15:56
-
-
Save benoittgt/ab12d245a5c13ba38eb93fdd71d109be to your computer and use it in GitHub Desktop.
Read an print zombie child process info in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ChildProcess | |
| class Ps | |
| attr_accessor :pid, :ppid, :state, :command | |
| def to_s | |
| "pid: '#{pid}', ppid: '#{ppid}', state: '#{state}', command: '#{command}'" | |
| end | |
| end | |
| attr_reader :list | |
| def initialize(ppid) | |
| @list = child_process_list(ppid) | |
| end | |
| def zombie_process | |
| @list.select { |child_process| child_process.state =~ /Z/ } | |
| end | |
| def zombie_process? | |
| @list.zombie_process(childs_process_list).any? | |
| end | |
| private | |
| def child_process_list(ppid) | |
| childs_process_list = [] | |
| ps_pipe = `ps -o pid=,ppid=,state=,args= | grep #{ppid}` | |
| ps_pipe.split(/\n/).map do |line| | |
| ps_part = line.split(/\s+/) | |
| next unless ps_part[1].to_i == ppid | |
| child_process = Ps.new | |
| child_process.pid = ps_part[0] | |
| child_process.ppid = ps_part[1] | |
| child_process.state = ps_part[2] | |
| child_process.command = ps_part[3..-1].join(' ') | |
| childs_process_list << child_process | |
| end | |
| childs_process_list | |
| end | |
| end | |
| pid = Process.pid | |
| puts "Current process pid : #{pid}" | |
| child_pids = [] | |
| 6.times.each do |i| | |
| child_pids << Process.fork do | |
| Process.setproctitle("rspec childp n #{i} with #{i * 3}s") | |
| puts "sleeping #{i * 3}s"; sleep i * 3 | |
| end | |
| end | |
| 10.times do | |
| puts ChildProcess.new(pid).zombie_process | |
| sleep 1 | |
| puts '----' | |
| end | |
| puts Process.waitall | |
| puts "Done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment