5,667,575 members and growing! (16,477 online)
Email Password   helpLost your password?
General Programming » Threads, Processes & IPC » General     Intermediate

Redirecting an arbitrary Console's Input/Output

By nickadams

Redirecting an arbitrary console's input/output in a simple, graceful way
VC6, VC7, VC7.1, C++Windows, Win2K, WinXP, Win2003, MFC, VS.NET2003, Visual Studio, Dev

Posted: 27 Nov 2003
Updated: 27 Nov 2003
Views: 137,168
Bookmarked: 60 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
40 votes for this Article.
Popularity: 7.39 Rating: 4.61 out of 5
0 votes, 0.0%
1
1 vote, 2.5%
2
0 votes, 0.0%
3
5 votes, 12.5%
4
34 votes, 85.0%
5

Sample Image - redir.gif

Introduction

To redirect the input/output of a console application is interesting and useful. You can display the child's output in a window (just like Visual Studio's output window), or search some keywords in the output string to determine if the child process has completed its work successfully. An old, 'ugly' DOS program could become an useful component of your fancy Win32 GUI program.

My idea is to develop a simple, easy to use redirector class which can redirect an arbitrary console, and won't be affected by the behavior of the child process.

Background

The technique of redirecting the input/output of a console process is very sample: The CreateProcess() API through the STARTUPINFO structure enables us to redirect the standard handles of a child console based process. So we can set these handles to either a pipe handle, file handle, or any handle that we can read and write. The detail of this technique has been described clearly in MSDN: HOWTO: Spawn Console Processes with Redirected Standard Handles.

However, MSDN's sample code has two big problem. First, it assumes the child process will send output at first, then wait for input, then flush the output buffer and exit. If the child process doesn't behave like that, the parent process will be hung up. The reason of this is the ReadFile() function remains blocked untill the child process sends some output, or exits.

Second, It has problem to redirect a 16-bit console (including console based MS-DOS applications.) On Windows 9x, ReadFile remains blocked even after the child process has terminated; On Windows NT/XP, ReadFile always returns FALSE with error code set to ERROR_BROKEN_PIPE if the child process is a DOS application.

Solving the block problem of ReadFile

To prevent the parent process from being blocked by ReadFile, we can simply pass a file handle as stdout to the child process, then monitor this file. A more simple way is to call PeekNamedPipe() function before calling ReadFile(). The PeekNamedPipe function checks information about data in the pipe, then returns immediately. If there's no data available in the pipe, don't call ReadFile.

By calling PeekNamedPipe before ReadFile, we also solve the block problem of redirecting a 16-bit console on Windows 9x.

The class CRedirector creates pipes and launchs the child process at first. then creates a listener thread to monitor the output of the child process. This is the main loop of the listener thread:

    for (;;)
    {
        // redirect stdout till there's no more data.

        nRet = pRedir->RedirectStdout();
        if (nRet <= 0)
            break;

        // check if the child process has terminated.

        DWORD dwRc = ::WaitForMultipleObjects(
            2, aHandles, FALSE, pRedir->m_dwWaitTime);
        if (WAIT_OBJECT_0 == dwRc)      // the child process ended

        {
            ...
            break;
        }
        if (WAIT_OBJECT_0+1 == dwRc)    // m_hEvtStop was signalled, exit

        {
            ...
            break;
        }
    }

This is the main loop of the RedirectStdout() function:

    for (;;)
    {
        DWORD dwAvail = 0;
        if (!::PeekNamedPipe(m_hStdoutRead, NULL, 0, NULL,
            &dwAvail, NULL))    // error, the child process might ended

            break;

        if (!dwAvail)           // no data available, return

            return 1;

        char szOutput[256];
        DWORD dwRead = 0;
        if (!::ReadFile(m_hStdoutRead, szOutput, min(255, dwAvail),
            &dwRead, NULL) || !dwRead)  
                 // error, the child process might ended

            break;

        szOutput[dwRead] = 0;
        WriteStdOut(szOutput);          // display the output

    }

WriteStdOut is a virtual member function. It does nothing in CRedirector class. However it can be overrided to achieve our specific target, like I did in the demo project:

    int nSize = m_pWnd->GetWindowTextLength();  
             // m_pWnd points to a multiline Edit control

    m_pWnd->SetSel(nSize, nSize);
    m_pWnd->ReplaceSel(pszOutput);      
           // add the message to the end of Edit control

To redirect DOS console based applications on NT/2000/XP

MSDN's solution is to launch an intermediate Win32 Console application as a stub process between the Win32 parent and the 16-bit console based child. In fact the DOS prompt program (on NT/XP it's cmd.exe, on 9x it's command.com) is a natural stub process we just need. We can test this in RedirDemo.exe:

  1. Input 'cmd.exe' in Command Editbox, then press Run button.
  2. Input the name of the 16-bit console based application (dosapp.exe for example) in the Input Editbox, then press Input button. Now we can see the output of the 16-bit consol.
  3. Input 'exit' in the Input Editbox, then press Input button to terminate cmd.exe

Apparently this is not a good solution because it's too complicated. A more effective way is to use a batch file as the stub. Edit stub.bat file like this:

%1 %2 %3 %4 %5 %6 %7 %8 %9

Then run a command like 'stub.bat dosapp.exe', then the 16-bit DOS console application runs OK.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

nickadams


Nick Adams is one of my favorite figures in Hemingway's stories. I use it because Jeff Lee has been occupied on Codeproject.

Occupation: Web Developer
Location: Canada Canada

Other popular Threads, Processes & IPC articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 56 (Total in Forum: 56) (Refresh)FirstPrevNext
GeneralTelnet.exemembertptshepo20:55 11 Nov '08  
Generalhow to send a CTRL+C???memberMotorcure0:08 17 Sep '08  
GeneralHow to you know when the process has ended?membermimosa14:28 21 Apr '08  
GeneralAbout Redirecting Debug IOmemberyonken1:26 6 Apr '08  
GeneralHow to change the bounds of bytes to output data at a time.memberchol92123:19 12 Nov '07  
Question.net portmemberneolode7:38 16 Sep '07  
GeneralOverlapped structuremembercharian092018:28 3 May '07  
GeneralAlso works for DLLs?memberroel hermans2:28 3 May '07  
GeneralWhat about advanced key events?membertorch#223:49 7 Mar '07  
GeneralAdapting To Windows Powershell?memberRobert T.10:33 25 Oct '06  
GeneralRe: Adapting To Windows Powershell?memberAnne Jan Beeks4:22 31 Jan '07  
GeneralRe: Adapting To Windows Powershell?memberRobert T.7:07 26 Mar '07  
GeneralRe: Adapting To Windows Powershell?memberAnne Jan Beeks7:32 26 Mar '07  
GeneralHow to avoid using fflush(); ?memberq.sa9:10 1 Oct '06  
QuestionAsking for help, Unexpected behavior with my client appmembergemex23:18 9 Aug '06  
GeneralCalling CRedirector::Close() in output thread problem !memberReivax721:26 14 Jun '06  
GeneralPlease Help me VBmemberWolverineSoft14:15 2 May '06  
General::SetConsoleCtrlHandler(CRedirector::CtrlHandler, TRUE);memberTcpip200523:06 25 Apr '06  
GeneralRe: ::SetConsoleCtrlHandler(CRedirector::CtrlHandler, TRUE);memberMotorcure16:33 17 Sep '08  
GeneralHow can i flush the clild's data?memberGalterian2:34 20 Feb '06  
GeneralWhy the telnet doesn't work with it?memberiamtony17:27 3 May '05  
GeneralRe: Why the telnet doesn't work with it?membernickadams5:01 4 May '05  
GeneralRe: Why the telnet doesn't work with it?memberosirisgothra8:07 6 Sep '07  
GeneralRedirecting Cygwin Consolemembersars15:35 14 Mar '05  
Generalprintf problem is not solved....memberMonk_2:18 10 Dec '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 27 Nov 2003
Editor: Nishant Sivakumar
Copyright 2003 by nickadams
Everything else Copyright © CodeProject, 1999-2008
Web15 | Advertise on the Code Project