Hide console window from CreateProcess and redirect ouput

Sometimes I need to create a process of console program and redirect its output to a file. It can be done via two simple steps:

1. Create a file handle which is inheritable:

SECURITY_ATTRIBUTES sa = {0};
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;

CAtlFile file;
HRESULT hr = file.Create(<file>, FILE_ALL_ACCESS, FILE_SHARE_READ, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, &sa);

2. Create the process with crafted start up information structure and flags containing CREATE_NO_WINDOW:

PROCESS_INFORMATION procinfo = {0};
STARTUPINFO startupinfo = {0};
startupinfo.cb = sizeof(startupinfo);
startupinfo.dwFlags = STARTF_USESTDHANDLES;
startupinfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
startupinfo.hStdOutput = file.m_h;
startupinfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);;
CreateProcess(NULL, (LPWSTR)(LPCWSTR)<cmdline>, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, NULL, NULL, &startupinfo, &procinfo);

More information get be obtained from “Redirecting an arbitrary Console’s Input/Output” on CodeProject as well as “How to spawn console processes with redirected standard handles” from MSDN.

Advertisements

Posted on March 8, 2011, in Uncategorized. Bookmark the permalink. Leave a comment.

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

%d bloggers like this: