0

我正在尝试确定给定 PID 的进程的当前工作目录。命令行实用程序 lsof 执行类似的操作。这是python脚本的源代码:

import ctypes
from ctypes import util
import sys

PROC_PIDVNODEPATHINFO = 9

proc = ctypes.cdll.LoadLibrary(util.find_library("libproc"))
print(proc.proc_pidinfo)

class vnode_info(ctypes.Structure):
    _fields_ = [('data', ctypes.c_ubyte * 152)]

class vnode_info_path(ctypes.Structure):
    _fields_ = [('vip_vi', vnode_info), ('vip_path', ctypes.c_char * 1024)]

class proc_vnodepathinfo(ctypes.Structure):
    _fields_ = [('pvi_cdir', vnode_info_path), ('pvi_rdir', vnode_info_path)]

inst = proc_vnodepathinfo()
pid = int(sys.argv[1])
ret = proc.proc_pidinfo( pid, PROC_PIDVNODEPATHINFO, 0, ctypes.byref(inst), ctypes.sizeof(inst) )
print(ret, inst.pvi_cdir.vip_path)

但是,即使此脚本在 Python 2.6 上的行为与预期一样,它在 Python 2.5 中也不起作用:

host:dir user$ sudo /usr/bin/python2.6 script.py 2698
<_FuncPtr object at 0x100419ae0>
(2352, '/')
host:dir user$ sudo /usr/bin/python2.5 script.py 2698
<_FuncPtr object at 0x19fdc0>
(0, '')

(PID 2698 是“活动监视器.app”)。注意不同的返回值。由于这个程序强烈地基于 ctypes,我无法想象 Python 本身有什么不同会导致这种情况。我自建的 Python 3.2 会出现相同的行为(与 Python 2.5 相同)。

我不确定我可以提供哪些版本控制信息来帮助追踪怪异——甚至想出一个 2.5 的解决方案——但这里有一些东西:

host:dir user$ otool -L /usr/bin/python2.6
/usr/bin/python2.6:
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
host:dir user$ otool -L /usr/bin/python2.5
/usr/bin/python2.5 (architecture i386):
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
/usr/bin/python2.5 (architecture ppc7400):
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)


host:dir user$ uname -a
Darwin host.local 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun  7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386

感谢任何对这里发生的事情有所了解的人:)

4

1 回答 1

0

我不确定您的代码有什么问题,但我刚刚在 psutil 中实现了这一点。这些是感兴趣的部分:

您可以决定在 ctypes 中翻译它,也可以编写自己的扩展模块。

于 2012-06-30T15:13:27.613 回答