Dave's Brain

Browse - programming tips - win32 how to use createprocess

Date: 2010apr30
OS: Windows

Language: C/C++


Q.  How to I used CreateProcess() ?

A.  Sorry 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 trail 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
// dwProcessId: [out] the process ID of the new process if it worked
BOOL ExecCommand(LPCSTR szExe, LPCSTR szCmdLine, 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 (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;
}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, 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.