Redirect Output of CMD.EXE to a Pipe

Environment: Visual C++ 6.0 SP2, Windows NT 4.0 SP4

I have the thought of redirecting output of WIN32 console programs to a pipe or a file long ago, but I don't know to do at all at first, finally I searched through Microsoft MSDN and found a way, the code pasted below was copied from MSDN sample code except some changes in function CreateChildProcess(), where I stressed in the code.

In the demo source, I redirect the stdout of CMD.exe to a pipe and start a thread to read from this pipe, then all that CMD.EXE output was redirected to the pipe where I am reading.


BOOL CShellView::CreateShellRedirect()
{
SECURITY_ATTRIBUTES saAttr;
BOOL fSuccess;

// Set the bInheritHandle flag so pipe handles are inherited.
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;

// The steps for redirecting child process's STDOUT:
// 1. Save current STDOUT, to be restored later.
// 2. Create anonymous pipe to be STDOUT for child process.
// 3. Set STDOUT of the parent process to be write handle to
// the pipe, so it is inherited by the child process.
// 4. Create a noninheritable duplicate of the read handle and
// close the inheritable read handle.

// Save the handle to the current STDOUT.
hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE);

// Create a pipe for the child process's STDOUT.
if( !CreatePipe( &hChildStdoutRd, &hChildStdoutWr, &saAttr, 0) )
{
TRACE0( _T("Stdout pipe creation failed\n") );
return FALSE;
}

// Set a write handle to the pipe to be STDOUT.
if( !SetStdHandle(STD_OUTPUT_HANDLE, hChildStdoutWr) )
{
TRACE0( _T("Redirecting STDOUT failed\n") );
return FALSE;
}

// Create noninheritable read handle and close the inheritable read handle.
fSuccess = DuplicateHandle( GetCurrentProcess(), hChildStdoutRd,
GetCurrentProcess(), &hChildStdoutRdDup ,
0, FALSE,
DUPLICATE_SAME_ACCESS );
if( !fSuccess )
{
TRACE0( _T("DuplicateHandle failed\n") );
return FALSE;
}
CloseHandle( hChildStdoutRd );

// The steps for redirecting child process's STDIN:
// 1. Save current STDIN, to be restored later.
// 2. Create anonymous pipe to be STDIN for child process.
// 3. Set STDIN of the parent to be the read handle to the
// pipe, so it is inherited by the child process.
// 4. Create a noninheritable duplicate of the write handle,
// and close the inheritable write handle.

// Save the handle to the current STDIN.
hSaveStdin = GetStdHandle(STD_INPUT_HANDLE);

// Create a pipe for the child process's STDIN.
if( !CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0) )
{
TRACE0( _T("Stdin pipe creation failed\n") );
return FALSE;
}
// Set a read handle to the pipe to be STDIN.
if( !SetStdHandle(STD_INPUT_HANDLE, hChildStdinRd) )
{
TRACE0( _T("Redirecting Stdin failed\n") );
return FALSE;
}
// Duplicate the write handle to the pipe so it is not inherited.
fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
GetCurrentProcess(), &hChildStdinWrDup,
0, FALSE, // not inherited
DUPLICATE_SAME_ACCESS );
if( !fSuccess )
{
TRACE0( _T("DuplicateHandle failed\n") );
return FALSE;
}
CloseHandle(hChildStdinWr);

// Now create the child process.
if( !CreateChildProcess(dwProcessId) )
{
TRACE0( _T("CreateChildProcess failed\n") );
return FALSE;
}
// After process creation, restore the saved STDIN and STDOUT.
if( !SetStdHandle(STD_INPUT_HANDLE, hSaveStdin) )
{
TRACE0( _T("Re-redirecting Stdin failed\n") );
return FALSE;
}
if( !SetStdHandle(STD_OUTPUT_HANDLE, hSaveStdout) )
{
TRACE0( _T("Re-redirecting Stdout failed\n") );
return FALSE;
}
m_pReadThread =
fxBeginThread( (AFX_THREADPROC)ReadPipeThreadProc,(LPVOID)this );
if( !m_pReadThread )
{
TRACE0( _T("Cannot start read-redirect thread!\n") );
return FALSE;
}
return TRUE;
}

BOOL CShellView::CreateChildProcess(DWORD& dwProcessId)
{
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;

// Set up members of STARTUPINFO structure.
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
siStartInfo.cb = sizeof(STARTUPINFO);
/////////////////////////////////////////
/*
Note here the
dwFlags should be STARTF_USESTDHANDLES, which is descripted in WIN32 API
document, but this was
omitted in MSDN sample
*/
siStartInfo.dwFlags = STARTF_USESTDHANDLES;
siStartInfo.hStdInput = hChildStdinRd;
siStartInfo.hStdOutput = hChildStdoutWr;
siStartInfo.hStdError = hChildStdoutWr;

///////////////////////////////////////////////////
TCHAR shellCmd[_MAX_PATH];
if( !GetEnvironmentVariable(_T("ComSpec"), shellCmd, _MAX_PATH) )
return FALSE;
#ifdef _UNICODE
_tcscat( shellCmd, _T(" /U") );
#else
_tcscat( shellCmd, _T(" /A") );
#endif
// Create the child process.
BOOL ret = CreateProcess( NULL,
shellCmd, // applicatin name
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
DETACHED_PROCESS, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
if( ret )
dwProcessId = piProcInfo.dwProcessId;
return ret;
}

Download source - 5 KB

Date Last Updated: April 4, 1999



Comments

  • Music Icons - Download 706 Free Music Icon (Page 1)

    Posted by lwexpeattiie.com on 12/12/2012 06:33pm

    By WebOsPublisher Cut,copy and paste icons : Icon « Dojo toolkit « JavaScript DHTML Cut, copy and paste icons : Icon « Dojo toolkit « JavaScript DHTML Cut, copy and paste icons : Icon « Dojo toolkit « JavaScript DHTMLHomeJavaScript DHTML1.Ajax Layer2.Data Type3.Date Time4.Development5.Document6.Dojo toolkit7.Event8.Event onMethod9.Ext JS10.Form Control11.GUI Components12.HTML13.Javascript Collections14.Javascript Objects15.Javascript Properties16.jQuery17.Language Basics18.Mochkit19.Mootools20.Node Operation21.Object Oriented22.Page Components23.Rico24.Scriptaculous25.Security26.SmartClient27.Style Layout28.Table29.Utilities30.Window Browser31.YUI LibraryJavaScript DHTML » Dojo toolkit » Icon Cut, copy and paste icons

    Cut
    Copy
    Paste
    Bold
    Dojo-toolkit.zip( 3,849 k) Related examples in the same category1.Italic icon2.Set icon class3.Add icon to button java2s.com | Contact Us | Privacy PolicyCopyright 2009 - 12 Demo Source and Support. All rights reserved.All other trademarks are property of their respective owners.

    Reply
  • Southard Body (promgtr) auf Twitter

    Posted by findicons.com on 12/12/2012 05:48pm

    By WebOsPublisher Database of supported phones in Gammu and Wammu,the software for managing GSM cell phones. Option GlobeSurferВ® iCON 7.2 - Gammu Phone Database [GW]ammu Support Download Screenshots Documentation Contribute Tools Option GlobeSurferВ® iCON 7.2 If this record contains wrong information, please add new record with correct information and the record will be replaced after review. All records were filled in by users and there is no guarantee that they are correct. More information about phone might be available on following sites: Wikipedia The Mobile Phone Directory Supported Features Phone information Sending and saving SMS Configuration [gammu] port = DEVICE NAME connection = at115200 Reporter Note work on sending and receive sms not tested on Basic phonebook functions (name and phone number) (phonebook) Enhanced phonebook entries (eg. several numbers per entry) (enhancedphonebook) Calendar entries (calendar) Todos (todo) Filesystem manipulation (filesystem) Reading and making calls (call) Logos (logo) Ringtones (ringtone) Multimedia messaging (mms) About entry Created by Mustaqim Alfarabi on April 18, 2010, 5:51 a.m.. Tested with Gammu 1.27.0. Page translations ДЊesky EspaГ±ol Deutsch SlovenДЌina FranГ§ais Translate! Navigation Phones Database Option Add new record Similar Phones None found. Donate Support Gammu by donating! Share Share Gammu with the world! Gammu on Google+ Gammu on Facebook Follow us on Twitter Follow us on Identi.ca About Gammu Wammu python-gammu SMSD Support Mailing lists Online Reporting bugs Commercial support Media Downloads Screenshots Third party News Documentation FAQ Supported phones Gammu Manual Configuration Contribute Translate Develop Donate Publicity Copyright © 2003 - 2012 Michal ДЊihaЕ™ License Donate Search Authors Valid HTML and CSS

    Reply
  • Under construction icons set | Grafika wektorowa В© Gladcov Vladimir #2952141

    Posted by iconshoco.com on 12/12/2012 04:17pm

    By WebOsPublisher This is caused by a bug in the Works add-in for Word. First uninstall the add-in (Windows > add & remove programs) then you can use tools > /** * vBulletin 3.8.7 CSS * Style: 'Default Style'; Style ID: 1 */ @import url("clientscript/vbulletin_css/style-d67de8a6-00001.css"); Re: Mail merge icons under tools Home Register Members Search Links Member Login: Search Forums Show Threads Show Posts Advanced Search Go to Page... Microsoft Office Forums > Microsoft Office Forums > Word > Word Newsgroups > Word Mail Merge > Re: Mail merge icons under tools Thread Tools Display Modes Re: Mail merge icons under tools Graham Mayor Guest Posts: n/a 08-09-2003, 09:00 AM This is caused by a bug in the Works add-in for Word. First uninstall the add-in (Windows > add $ remove programs) then you can use tools > customize in Word to drag off the unwanted entries. -- <>>< ><<> ><<> <>>< ><<> <>>< <>>< ><<> Graham Mayor - Word MVP E-mail (E-Mail Removed) Web site gmayor.dsl.pipex.com Word MVP web site mvps.org/word <>>< ><<> ><<> <>>< ><<> <>>< <>>< ><<> Tim OConner wrote: > Every time I print an envelope it creates another mail > merge icon under tools. Now when I select tools (at the > top of my Word 2000) it opens and looks like this: > > mail merge... > mail merge... > mail merge... > mail merge... > mail merge... > mail merge... > mail merge... > mail merge... > mail merge... > mail merge... > envelopes and labels... > letter wizard... > > How do I delete all of these mail merge icons? « Resume distribution | Re: merge field over picture » Thread Tools Show Printable Version Email this Page Display Modes Linear Mode Switch to Hybrid Mode Switch to Threaded Mode Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules Similar Threads Thread Thread Starter Forum Replies Last Post mail merge in Publisher - can't access mail merge thru "TOOLS" Becky Publisher Newsgroups 5 05-24-2006 07:48 PM How do I mail merge when only merge document is shown in tools? DaveAS Word Documents 2 12-01-2004 03:45 PM I HAVE NO MAIL MERGE UNDER TOOLS MENU. I AM TRYING TO MALE MAIL.. Alex@islands.vi Word Mail Merge 1 09-15-2004 10:07 AM NO 'Mail Merge' Command in ! EDP Word Mail Merge 1 04-05-2004 07:45 AM Mail merge in tools pulldown box Mark Word Mail Merge 1 01-06-2004 05:38 PM All times are GMT. The time now is 08:02 AM. Microsoft Office Forums is not affiliated with Microsoft Corporation. Powered by vBulletin® Version. Copyright ©2000 - 2008, Jelsoft Enterprises Ltd. SEO by vBSEO 3.3.2 ©2009, Crawlability, Inc. Contact Us - Microsoft Office Forums - Archive - Privacy Statement - Top

    Reply
  • IMVU Tutorial on Fake Hair in Photoshop | eHow.com

    Posted by janjan..in on 12/12/2012 03:57pm

    By WebOsPublisher Paste icons. Download more than 150,000 icons in PNG or ICO format. Paste icons | Icon Search Engine | 2 (function())(); Search Browse Newest icon sets Popular icon sets Largest icon sets Tags Alphabetic list About About IconFinder API Labs Terms of service Help & Support Blog Submit icons Get early access to our marketplace Paginated Continuous Background color 0 px12 px16 px24 px32 px48 px64 px128 px256 px512 px0 px12 px16 px24 px32 px48 px64 px128 px256 px512 px No license filtering Allowed for commercial use Allowed for commercial use (No link required) Paste icons - 49 - 96 of about 96. Related searches: clipboard, edit, document, gtk INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO INFO Please wait PNG ICO « Previous12 © Iconfinder 2012 - Free icons - Labs - Made in Copenhagen

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds