Dave's Brain

Browse - Programming Tips - How do I use CreateProcess() ?

Date: 2010apr30
OS: Windows
Language: C/C++

Q.  How do I use CreateProcess() ?

A.  Sooner or later you'll want something more powerful than WinExec().
The next step up is CreateProcess() but its not easy to use.
It took me some trial and error to figure this out.
Here is a function called ExecCommand() launches a new process
and gets the process ID back.

// szExe: [in] full path to the .exe file you want to run // szCmdLine: [in] the command followed by any option you want // bWait: [in] wait for the command to run? // dwProcessId: [out] the process ID of the new process if it worked BOOL ExecCommand(LPCSTR szExe, LPCSTR szCmdLine, BOOL bWait, DWORD &dwProcessId) { STARTUPINFO si; PROCESS_INFORMATION pi; BOOL bResult; dwProcessId = 0; ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); // You need to set the size or it doesn't work ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); bResult = CreateProcess( (LPSTR)szExe, // pointer to name of executable module (LPSTR)szCmdLine, // pointer to command line string NULL, // pointer to process security attributes NULL, // pointer to thread security attributes FALSE, // handle inheritance flag 0, // creation flags NULL, // pointer to new environment block NULL, // pointer to current directory name &si, // pointer to STARTUPINFO &pi // pointer to PROCESS_INFORMATION );
if (bWait) { DWORD timeout_seconds = 10;
WaitForSingleObject(pi.hProcess, timeout_seconds * 1000); } if (bResult) { dwProcessId = pi.dwProcessId; // You get back two open handles if the process has been successfull created. // But, in this case, we don't want them so close them so we don't leak handles. CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } else { DWORD dwError = GetLastError(); // You can do something with dwError here if you want } return bResult; }
See also http://www.davekb.com/search.php?target=WinExec

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.