1

我正在尝试使用 kernel32.CreateProcessA 在 python 中运行一个进程。我的代码在下面,正在运行的脚本只返回-1(因此名称为 Returns-1.py)。但是,当我访问退出代码值(以我认为正确的方式)时,我得到 0。我无法理解如何访问应该为 -1 的返回代码。非常感谢任何建议。

from ctypes import *

HANDLE = c_void_p
LPVOID = c_void_p
DWORD = c_ulong
WORD = c_ushort
CHAR = c_char
ULONG = c_ulong
LPSTR = POINTER(CHAR)
BYTE = c_char
LPBYTE = POINTER(BYTE)
LPDWORD = POINTER(DWORD)

#http://msdn.microsoft.com/en-us/library/windows/desktop/ms684873(v=vs.85).aspx
class ProcessInfo(Structure):
    _fields_ = [('hProcess', HANDLE),
            ('hThread', HANDLE),
            ('dwProcessId', DWORD),
            ('dwThreadId', DWORD),
           ]

#http://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx
class StartupInfo(Structure):
    _fields_ = [ ('cb', DWORD),
        ('lpReserved', LPSTR),
        ('lpDesktop', LPSTR),
        ('lpTitle', LPSTR),
        ('dwX', DWORD),
        ('dwY', DWORD),
        ('dwXSize', DWORD),
        ('dwYSize', DWORD),
        ('dwXCountChars', DWORD),
        ('dwYCountChars', DWORD),
        ('dwFillAttribute', DWORD),
        ('dwFlags', DWORD),
        ('wShowWindow', WORD),
        ('cbReserved2', WORD),
        ('lpReserved2', LPBYTE),
        ('hStdInput', HANDLE),
        ('hStdOutput', HANDLE),
        ('hStdError', HANDLE),
        ]

class ExitCodeProcess(Structure):
    _fields_ = [ ('hProcess', HANDLE),
        ('lpExitCode', LPDWORD)]

pi = ProcessInfo()
si = StartupInfo()
#Running cmd in a new process
#http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx
success = kernel32.CreateProcessA(c_char_p(0),
                                 c_char_p("python Returns-1.py"),
                                 0,
                                 0,
                                 0,
                                 1, #follow forks
                                 0,
                                 0,
                                 byref(si),
                                 byref(pi))


#CODE TO ACCESS RETURN CODE
c_long_p = POINTER(c_long)
ec = ExitCodeProcess()
success = kernel32.GetExitCodeProcess(pi.hProcess, byref(ec))
print "success is:", success   #prints success is: 1
print str(cast(addressof(ec.lpExitCode), c_long_p).contents) #prints 'c_long(0)' not -1
4

1 回答 1

0

好吧,这个有点旧,但对于那些寻求答案的人来说。有太多不必要的引用和指针强制转换。做起来更容易:

ec = DWORD()
if not kernel32.GetExitCodeProcess(process_information.hProcess, byref(ec)):
    print "Error in getting exit code: " + str(kernel32.GetLastError())
else:
    print "Exit code: " + str(ec.value)
于 2016-07-07T09:54:47.640 回答