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

余生颓废 提交于 2019-12-22 10:23:38

问题


The documentation for QProcess.pid() says:

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

What does this mean?

This code is used to explain my confusion. I am using Python 2.7.9, PyQt 4 and 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_())

This launches the Windows calculator application, as expected. In the task manager, it shows the following:

This shows my PID as 8304. The print statement from my application though, shows:

PID: 44353984

What does this represent and how does it compare to the 8304 PID the task manager reports?


回答1:


On Unix systems, the pid will be a qint64, but on Windows it will be struct like this:

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

PyQt will return a sip.voidptr for such a struct, which is why you are seeing that weird value when you convert it with int(). The actual pid you want is the dwProcessId, so you will need to use something like ctypes to extract it.

Here is some completely untested code which might do the job:

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)


来源:https://stackoverflow.com/questions/32509089/when-using-pyqt-on-windows-what-does-the-qprocess-pid-result-represent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!