在 Windows 上使用 pyqt 时, QProcess.pid() 结果代表什么?

When using pyqt on Windows, what does the QProcess.pid() result represent?

QProcess.pid() 的文档说:

Returns the native process identifier for the running process, if available. If no process is currently running, 0 is returned.

这是什么意思?

这段代码用来解释我的困惑。我正在使用 Python 2.7.9、PyQt 4 和 Windows 7:

import  sys, os, time
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class testLaunch(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.process = QProcess(self)
        self.process.start('calc')
        self.process.waitForStarted(1000)
        print "PID:", int(self.process.pid())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = testLaunch()
    main.show()
    sys.exit(app.exec_())

这将按预期启动 Windows 计算器应用程序。在任务管理器中,显示如下:

这显示我的 PID 为 8304。我的应用程序的 print 语句显示:

PID: 44353984

这代表什么,它与任务管理器报告的 8304 PID 相比如何?

在 Unix 系统上,pid 将是 qint64,但在 Windows 上它将是 struct,如下所示:

typedef struct _PROCESS_INFORMATION {
  HANDLE hProcess;
  HANDLE hThread;
  DWORD  dwProcessId;
  DWORD  dwThreadId;
} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;

PyQt 将为这样的结构 return 一个 sip.voidptr,这就是为什么当你用 int() 转换它时你会看到那个奇怪的值。你想要的实际 pid 是 dwProcessId,所以你需要使用类似 ctypes 的东西来提取它。

这里有一些完全未经测试的代码可能会完成这项工作:

import ctypes

class WinProcInfo(ctypes.Structure):
    _fields_ = [
        ('hProcess', ctypes.wintypes.HANDLE),
        ('hThread', ctypes.wintypes.HANDLE),
        ('dwProcessID', ctypes.wintypes.DWORD),
        ('dwThreadID', ctypes.wintypes.DWORD),
        ]
LPWinProcInfo = ctypes.POINTER(WinProcInfo)

lp = ctypes.cast(int(self.process.pid()), LPWinProcInfo)
print(lp.contents.dwProcessID)