def getPwd(pid): """ Provices the working directory of the given process. This raises an IOError if it can't be determined. Arguments: pid - pid of the process """ if not pid: raise IOError("we couldn't get the pid") elif pid in PWD_CACHE: return PWD_CACHE[pid] # try fetching via the proc contents if available if procTools.isProcAvailable(): try: pwd = procTools.getPwd(pid) PWD_CACHE[pid] = pwd return pwd except IOError: pass # fall back to pwdx elif os.uname()[0] in ("Darwin", "FreeBSD", "OpenBSD"): # BSD neither useres the above proc info nor does it have pwdx. Use lsof to # determine this instead: # https://trac.torproject.org/projects/tor/ticket/4236 # # ~$ lsof -a -p 75717 -d cwd -Fn # p75717 # n/Users/atagar/tor/src/or try: results = call("lsof -a -p %s -d cwd -Fn" % pid) if results and len(results) == 2 and results[1].startswith("n/"): pwd = results[1][1:].strip() PWD_CACHE[pid] = pwd return pwd except IOError, exc: pass try: # pwdx results are of the form: # 3799: /home/atagar # 5839: No such process results = call("pwdx %s" % pid) if not results: raise IOError("pwdx didn't return any results") elif results[0].endswith("No such process"): raise IOError("pwdx reported no process for pid " + pid) elif len(results) != 1 or results[0].count(" ") != 1: raise IOError("we got unexpected output from pwdx") else: pwd = results[0][results[0].find(" ") + 1:].strip() PWD_CACHE[pid] = pwd return pwd except IOError, exc: raise IOError("the pwdx call failed: " + str(exc))
def getPwd(pid): """ Provices the working directory of the given process. This raises an IOError if it can't be determined. Arguments: pid - pid of the process """ if not pid: raise IOError("we couldn't get the pid") elif pid in PWD_CACHE: return PWD_CACHE[pid] # try fetching via the proc contents if available if procTools.isProcAvailable(): try: pwd = procTools.getPwd(pid) PWD_CACHE[pid] = pwd return pwd except IOError: pass # fall back to pwdx try: # pwdx results are of the form: # 3799: /home/atagar # 5839: No such process results = call("pwdx %s" % pid) if not results: raise IOError("pwdx didn't return any results") elif results[0].endswith("No such process"): raise IOError("pwdx reported no process for pid " + pid) elif len(results) != 1 or results[0].count(" ") != 1: raise IOError("we got unexpected output from pwdx") else: pwd = results[0][results[0].find(" ") + 1:].strip() PWD_CACHE[pid] = pwd return pwd except IOError, exc: raise IOError("the pwdx call failed: " + str(exc))