Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Created June 8, 2016 08:16
Show Gist options
  • Save cslarsen/7e2ae926706f9d18287fdbc87850eb0f to your computer and use it in GitHub Desktop.
Save cslarsen/7e2ae926706f9d18287fdbc87850eb0f to your computer and use it in GitHub Desktop.

Revisions

  1. cslarsen created this gist Jun 8, 2016.
    51 changes: 51 additions & 0 deletions pids.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    #!/usr/bin/env python3

    from collections import defaultdict
    import os
    import sys

    def read_cmdline(file):
    try:
    with open(file, "rb") as f:
    cmd = str(f.read(), encoding="utf-8")
    if cmd is not None:
    return cmd.replace("\x00", " ")
    except:
    pass

    def getprogs():
    # Index on the basename of cmdline
    basenames = defaultdict(lambda: [])
    # Index on the full command line
    fullnames = defaultdict(lambda: [])

    for pid in os.listdir("/proc/"):
    if pid.isdigit():
    pid = int(pid)
    cmd = read_cmdline("/proc/%d/cmdline" % pid)
    if cmd is not None:
    basenames[os.path.basename(cmd.split(" ")[0])].append(pid)
    fullnames[cmd].append(pid)
    return basenames, fullnames

    if __name__ == "__main__":
    if ("-h" in sys.argv) or ("--help" in sys.argv):
    print("Usage: pid name [ name]")
    print("Returns pids of program basenames.")
    print("Example: pid vim # prints pids for all vim procs")
    sys.exit(0)

    self = os.getpid()

    basenames, fullnames = getprogs()
    for prog in sys.argv[1:]:
    if prog in basenames:
    for pid in basenames[prog]:
    if pid != self:
    print(pid)
    else:
    for cmd, pids in fullnames.items():
    if prog in cmd:
    for pid in pids:
    if pid != self:
    print(pid)