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 = { 0 }; PROCESS_INFORMATION pi = { 0 }; dwProcessId = 0; si.cb = sizeof(STARTUPINFO); // You need to set the size or it doesn't work const BOOL 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) { DWORD dwError = GetLastError(); // You can do something with dwError here if you want return bResult; } dwProcessId = pi.dwProcessId; // You get back two open handles if the process has been successfully 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); return bResult; }
See also