Saturday, May 30, 2009

system call without console window

I just finisehd a system like function that is loosely based on the C runtime's system function.

The goal is to run a system command without a console window being displayed.

Also uses the safe string functions.

Here it is:

#include

int SystemNoWindow(const TCHAR *command)
{

int retval = 0;
TCHAR *cmdbuf = 0;
TCHAR *CommandLine = 0;

cmdbuf = (TCHAR *)calloc(MAX_PATH,sizeof(TCHAR));
if (!cmdbuf)
goto cleanup; // alloc fail

GetEnvironmentVariable(_T("COMSPEC"),cmdbuf,MAX_PATH);

STARTUPINFO StartupInfo;
PROCESS_INFORMATION ProcessInformation;

memset(&StartupInfo,0,sizeof(StartupInfo));
StartupInfo.cb = sizeof(StartupInfo);

size_t bufferSize;
if ( StringCbLength(command,MAX_PATH,&bufferSize) != S_OK)
goto cleanup; // length size fail

size_t cmdbufSize;
if (StringCbLength(cmdbuf,MAX_PATH,&cmdbufSize) != S_OK)
goto cleanup; // length size fail

bufferSize += cmdbufSize + 5;

CommandLine = (TCHAR *)calloc(bufferSize,sizeof(TCHAR));
if (!CommandLine)
goto cleanup; // alloc fail

if (StringCchCopy(CommandLine,bufferSize,cmdbuf) != S_OK)
goto cleanup; // copy fail

if (StringCchCat(CommandLine,bufferSize,_T(" /C ")) != S_OK)
goto cleanup; // strcat fail

if (StringCchCat(CommandLine,bufferSize,command) != S_OK)
goto cleanup; // strcat fail

BOOL cpWorked = CreateProcess( NULL, CommandLine,NULL,NULL,
TRUE,CREATE_NO_WINDOW,
NULL,NULL,
&StartupInfo,
&ProcessInformation
);

if (!cpWorked)
goto cleanup; // CreateProcess fail

WaitForSingleObject(ProcessInformation.hProcess, (DWORD)(-1));

DWORD exitcode;
GetExitCodeProcess(ProcessInformation.hProcess, &exitcode);

retval = (intptr_t)(int)exitcode;

CloseHandle(ProcessInformation.hProcess);

cleanup:
free(CommandLine);
free(cmdbuf);

return retval;

}

Note: the C-runtime functions use Goto to avoid exception handling, not my preference but I chose to follow the model.

No comments:

chris' shared items

Twitter Updates

Official blog of Chris Lee Runyan

Fastest C++ in the west.