OLD | NEW |
(Empty) | |
| 1 #!/usr/bin/env python |
| 2 |
| 3 # This Source Code Form is subject to the terms of the Mozilla Public |
| 4 # License, v. 2.0. If a copy of the MPL was not distributed with this file, |
| 5 # You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
| 7 import os |
| 8 import mozinfo |
| 9 import shlex |
| 10 import subprocess |
| 11 import sys |
| 12 |
| 13 # determine the platform-specific invocation of `ps` |
| 14 if mozinfo.isMac: |
| 15 psarg = '-Acj' |
| 16 elif mozinfo.isLinux: |
| 17 psarg = 'axwww' |
| 18 else: |
| 19 psarg = 'ax' |
| 20 |
| 21 def ps(arg=psarg): |
| 22 """ |
| 23 python front-end to `ps` |
| 24 http://en.wikipedia.org/wiki/Ps_%28Unix%29 |
| 25 returns a list of process dicts based on the `ps` header |
| 26 """ |
| 27 retval = [] |
| 28 process = subprocess.Popen(['ps', arg], stdout=subprocess.PIPE) |
| 29 stdout, _ = process.communicate() |
| 30 header = None |
| 31 for line in stdout.splitlines(): |
| 32 line = line.strip() |
| 33 if header is None: |
| 34 # first line is the header |
| 35 header = line.split() |
| 36 continue |
| 37 split = line.split(None, len(header)-1) |
| 38 process_dict = dict(zip(header, split)) |
| 39 retval.append(process_dict) |
| 40 return retval |
| 41 |
| 42 def running_processes(name, psarg=psarg, defunct=True): |
| 43 """ |
| 44 returns a list of |
| 45 {'PID': PID of process (int) |
| 46 'command': command line of process (list)} |
| 47 with the executable named `name`. |
| 48 - defunct: whether to return defunct processes |
| 49 """ |
| 50 retval = [] |
| 51 for process in ps(psarg): |
| 52 command = process['COMMAND'] |
| 53 command = shlex.split(command) |
| 54 if command[-1] == '<defunct>': |
| 55 command = command[:-1] |
| 56 if not command or not defunct: |
| 57 continue |
| 58 if 'STAT' in process and not defunct: |
| 59 if process['STAT'] == 'Z+': |
| 60 continue |
| 61 prog = command[0] |
| 62 basename = os.path.basename(prog) |
| 63 if basename == name: |
| 64 retval.append((int(process['PID']), command)) |
| 65 return retval |
| 66 |
| 67 def get_pids(name): |
| 68 """Get all the pids matching name""" |
| 69 |
| 70 if mozinfo.isWin: |
| 71 # use the windows-specific implementation |
| 72 import wpk |
| 73 return wpk.get_pids(name) |
| 74 else: |
| 75 return [pid for pid,_ in running_processes(name)] |
| 76 |
| 77 if __name__ == '__main__': |
| 78 pids = set() |
| 79 for i in sys.argv[1:]: |
| 80 pids.update(get_pids(i)) |
| 81 for i in sorted(pids): |
| 82 print i |
OLD | NEW |