Tips for CreateProcess Win32 API function

The CreateProcess() Win32 API function is actually difficult to use. Don’t you think so? Read on.

1. Repeat an executable name in lpApplicationName and lpCommandLine.
Otherwise OS may fail to separate an executable from the rest of command line when the executable filename contains a space.

2. Quote the executable name in lpCommandLine in even if you do (1).
Otherwise the child process gets confused to find the name of itself (argv[0]) when the executable name contains a space.

3. Use quote only in lpCommandLine .
CreateProcess() fails if quote is used in lpApplicationName.

4. Close hProcess and hThread handles in PROCESS_INFORMATION structure.
Otherwise you have a resource leak bug.

5. lpCommandLine is not const.
And it’s actually modified by the API. Therefore, you cannot, for example, use a string literal.

So, here is the correct usage of CreateProcess() API.

 

int main(){
using namespace std;

STARTUPINFOW si; ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);

PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));

WCHAR wszCommandLine[MAX_PATH];
wcscpy(wszCommandLine, L""S:\path with space\child.exe" arg1");
BOOL bResult = ::CreateProcessW(L"S:\path with space\child.exe",
wszCommandLine,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi);

if(bResult){
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}else{
cout << "Failed to start process" << endl;
}
return 0;
}

Advertisements

About Moto

Engineer who likes coding
This entry was posted in Tips. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s