Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use /proc instead of ps on linux #3

Merged
merged 2 commits into from Jun 19, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 28 additions & 1 deletion src/shellingham/posix.py
@@ -1,5 +1,7 @@
import collections
import os
import platform
import re
import shlex
import subprocess
import sys
Expand Down Expand Up @@ -30,11 +32,36 @@ def _get_process_mapping():
return processes


def _linux_get_process_mapping():
"""Try to look up the process tree via linux's /proc"""
STAT_PPID = 3
STAT_TTY = 6
with open('/proc/%s/stat' % os.getpid()) as f:
self_tty = f.read().split()[STAT_TTY]
pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
processes = {}
for pid in pids:
try:
with open('/proc/%s/stat' % pid) as fstat, open('/proc/%s/cmdline' % pid) as fcmdline:
stat = re.findall('\(.+\)|\S+', fstat.read())
cmd = fcmdline.read().split('\x00')[:-1]
ppid = stat[STAT_PPID]
tty = stat[STAT_TTY]
if tty == self_tty:
processes[pid] = Process(
args=tuple(cmd), pid=pid, ppid=ppid,
)
except IOError:
# process has disappeared - just ignore it
pass
return processes


def get_shell(pid=None, max_depth=6):
"""Get the shell that the supplied pid or os.getpid() is running in.
"""
pid = str(pid or os.getpid())
mapping = _get_process_mapping()
mapping = _linux_get_process_mapping() if platform.system() == 'Linux' else _get_process_mapping()
login_shell = os.environ.get('SHELL', '')
for _ in range(max_depth):
try:
Expand Down