I am attempting to run a process in python using kernel32.CreateProcessA. My code is below, and the script being run simply returns -1 (hence the name Returns-1.py). However, when I access the exit code value (in the manner I believe is correct), I get 0. I cannot understand how to access the return code which should be -1. Any advice is much appreciated.
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
Well, this one is kinda old, but for those who seek an answer. There are too many unnecessary reference and pointers casts. Do it easier: