Search code examples
rubywindowspid

Windows Ruby get PID from process name


So I do realize a similar question has been asked Find a process ID by name but the thing is, it really returns all PIDs with their names, including the spawned children of that process. My question is how can I only get the PID of the parent process and not one of it's children?


Solution

  • The sys-proctable gem can do that, here is a minimal example for getting the PID of the ruby.exe process on the system:

    require 'sys/proctable'
    
    def get_process_id(name)
        Sys::ProcTable.ps.detect{|p| p.name == name}&.pid
    end
    
    puts get_process_id("ruby.exe")
    

    That doesn't guarantee you will find the parent process tho, you will instead get the process with the lowest PID.

    To actually find the "root process", you need to further select processes by checking if their parent process is either non-existent or a different process:

    require 'sys/proctable'
    
    def get_parent_process_id(name)
        # generate a hash mapping pid -> process info
        processes = Sys::ProcTable.ps.map{|p| [p.pid, p]}.to_h
    
        # find the first matching process that has either no parent or a parent
        # that doesn't match the process name we're looking for
        processes.values.each do |p| 
            next if p.name != name
    
            if processes[p.ppid].nil? || processes[p.ppid].name != name
                return p.pid
            end
        end
    
        nil
    end
    
    puts get_parent_process_id("chrome.exe")