Capturing output from console program

Posted on 1998-06-01
Last Modified: 2013-12-03
Why does this work differently on some machines and how
can I fix it???  To run it set up a shortcut for then program (external.exe) then add command line
parameters (ie: change Target: C:\test\external.exe c:\dos\pkunzip -v c:\new\*.zip). Oh and just
to be sure you know, the program is supposed to kick off a dos or console application and
display the output in the window only.

Machine #1
      Zenith Pentium 100
      Win95 ver 4.00.095
      Works perfectly!!!

Machine #2
      Compaq Pentium 200
      Win95 ver 4.00.111
      Checks floppy drive and external program never runs, produces no output

Machine #3
      Micron Pentium 200
      Win95 ver 4.00.111
      Checks floppy drive and then external program starts and produces output fine.

Here's the source code :

#include <windows.h>
#include <windowsx.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <process.h>

//************* FUNCTION DECLARATIONS *****************************
int pascal WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpszCmdParam, int nCmdShow);
long CALLBACK MainWndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void command_external(void);
VOID ReadFromPipe(void);
void show_error_text(void);

//**************** SOME GLOBALS VARIABLES **************************
HANDLE      hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
                        hChildStdoutRd, hChildStdoutWr,
                        hInputFile, hSaveStdin, hSaveStdout;
DWORD            dwRead, dwAvail, dwUnRead, dwExitCode, dwWrite;
DWORD            dwStartup;
char            chBuf[4096];
char            ExternalCommandLine[2048];
BOOL            peek_result;
HWND            ghWnd;
HINSTANCE      ghInst;
HFONT            hfont;

//****************** START OF PROGRAM **************************
int pascal WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpszCmdParam, int nCmdShow)
  HWND hWnd;
  MSG Msg;

  memset(&wc, 0, sizeof(WNDCLASS)); = CS_HREDRAW | CS_VREDRAW;
  wc.lpfnWndProc = MainWndProc;
  wc.hInstance = hInst;
  wc.hIcon = NULL; //LoadIcon( hInst, MAKEINTRESOURCE( IDI_MAIN_ICON ) );
  wc.hbrBackground = GetStockObject(WHITE_BRUSH);
  wc.lpszClassName = "DS-External";

  hWnd = CreateWindow("DS-External", //classname
                      "DS-External", //winname
                      0, 0,
                      640, 480,
                      NULL );

  ghWnd = hWnd;
  ghInst = hInst;

  ShowWindow(hWnd, nCmdShow);

      hfont = CreateFont(      12,5,
                                                                  FF_MODERN | FIXED_PITCH,

      while ( GetMessage( &Msg, NULL, 0, 0 ) )
  return (Msg.wParam);

long CALLBACK MainWndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
  RECT hDesktopRect, hWndRect;

    case WM_CREATE:
                  DWORD thread_id;
                  HANDLE hThread;

      GetClientRect( GetDesktopWindow(), &hDesktopRect);
      GetWindowRect(hWnd, &hWndRect);
      SetWindowPos(hWnd, (HWND) NULL,
        (hDesktopRect.right / 2) - ((hWndRect.right-hWndRect.left)  / 2),
                        (hDesktopRect.bottom / 2) - (( / 2) - 16,
                  if((hThread = CreateThread(
                                                                        &thread_id)) == NULL)
                        MessageBox(ghWnd,"**** Failed to create External Thread ****","Error",MB_OK);
      return(0); //Continue Creation
    case WM_DESTROY:
      return (DefWindowProc(hWnd, message, wParam, lParam));

void command_external(void)
  BOOL fSuccess;

      saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  saAttr.bInheritHandle = TRUE;
  saAttr.lpSecurityDescriptor = NULL;
      // Create a pipe for the child's STDOUT.
  if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 4096))
      MessageBox(ghWnd,"Stdout pipe creation failed\n","Error",MB_OK);
  // Set a write handle to the pipe to be STDOUT.
  if (! SetStdHandle(STD_OUTPUT_HANDLE, hChildStdoutWr))
      MessageBox(ghWnd,"Redirecting STDOUT failed","Error",MB_OK);

  // Create a pipe for the child's STDIN.
  if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 4096))
      MessageBox(ghWnd,"Stdin pipe creation failed\n","Error",MB_OK);
  // Set a read handle to the pipe to be STDIN.
  if (! SetStdHandle(STD_INPUT_HANDLE, hChildStdinRd))
      MessageBox(ghWnd,"Redirecting Stdin failed","Error",MB_OK);
  // Duplicate the write handle to the pipe so it is not inherited.
  fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
      GetCurrentProcess(), &hChildStdinWrDup, 0,
      FALSE,       // not inherited
  if (! fSuccess)
        MessageBox(ghWnd,"DuplicateHandle failed","Error",MB_OK);
  // Now create the child process.
  // Set up members of STARTUPINFO structure.
  siStartInfo.cb = sizeof(STARTUPINFO);
  siStartInfo.lpReserved = NULL;
  siStartInfo.lpReserved2 = NULL;
  siStartInfo.cbReserved2 = 0;
  siStartInfo.lpDesktop = NULL;
  //siStartInfo.dwFlags = 0;
      siStartInfo.dwFlags = STARTF_USESTDHANDLES;
      siStartInfo.hStdInput = hChildStdoutRd;
      siStartInfo.hStdOutput = hChildStdoutWr;
  // Create the child process.
      &piProcInfo) == FALSE)
            MessageBox(ghWnd,"Create process failed","Error",MB_OK);


      MessageBox(ghWnd,"external command Completed!","Done",MB_OK);

VOID ReadFromPipe(void)
  DWORD dwRead, dwAvail, dwUnRead, dwExitCode;
  char chBuf[4096];
  HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
      BOOL peek_result;
      BOOL any_output;
      int posx,posy,chidx;
      HDC hdc;

      posx = 0; posy = 0;
   * Close the write end of the pipe before reading from the
   * read end of the pipe.
  if (! CloseHandle(hChildStdoutWr))
      MessageBox(ghWnd,"Closing handle failed","Error",MB_OK);

  /* Read output from child, and write it to parent's STDOUT. */

      any_output = FALSE;
  for (;;)
            peek_result = PeekNamedPipe(hChildStdoutRd,chBuf,4096,&dwRead, &dwAvail, &dwUnRead);
            if((dwRead == 0) && (dwAvail == 0) && (dwUnRead == 0))
                  //if process has finished  createprocess
                  if(dwExitCode != STILL_ACTIVE)
                        if(any_output == TRUE)
                              peek_result = PeekNamedPipe(hChildStdoutRd,chBuf,4096,&dwRead, &dwAvail, &dwUnRead);
                              if((dwRead == 0) && (dwAvail == 0) && (dwUnRead == 0))
                                    peek_result = TRUE;
            ReadFile(hChildStdoutRd, chBuf, 4096, &dwRead, NULL);
            //*********** output text to window ***********
            hdc = GetDC(ghWnd);
            for(chidx = 0; chidx < (int)dwRead; chidx++)
                        case 10:
                        case 13:
                              posy += 12;
                              posx = 0;
                              posx += 5;
            ReleaseDC(ghWnd, hdc);
            any_output = TRUE;

void show_error_text(void)
      char tmpstr[256];
      char tmpstr2[280];
      DWORD lerror_num;

      lerror_num = GetLastError();
      sprintf(tmpstr2,"Error %li = %s",lerror_num,tmpstr);

Question by:bbarber
  • 5
  • 4
LVL 23

Expert Comment

ID: 1405630
Take the following samples and run them on the three machines. If you encounter the same problem, your program should be OK. Otherwise, you need to look into these samples to see what is wrong with your program.

How to Spawn a Console App and Redirect Standard Handles

Redirection Issues on Windows 95 MS-DOS Apps and Batch Files


Author Comment

ID: 1405631
The artical's referenced in your response where unreachable and the pointers failed

Can you check them and resubmit?
LVL 23

Expert Comment

ID: 1405632
Microsoft seems to have removed the first KB article. You can get it from MSDN Library CDs. This article does not contain much information.

Author Comment

ID: 1405633
Well thats about the worst answer I've ever seen.  If I had all the resouces that you have, dont you think I would have already looked at them and gotten past that.  I wrote this based on the referenced examples.  I ask for a reason whay this didn't work and how to make it work.  Not do you know any references.  Now I know how you got such a hige Expert score.
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

LVL 23

Expert Comment

ID: 1405634
You seem to not get the key of my (worst) answer. I suspected that there is something wrong with the machines not your code. So, I asked you to run the samples on these machines to see what happens. Have you tried?

Well, I admit that this is one of my worst answers. It is just a guess.

Regarding my score, if you take a look at the questions I answered, you'll see that I have never cared about the points while some other Experts asked the customers to pay more points. I agree that the points are the credits the customers should give to the Experts because the Experts do their jobs here without any other remuneration. I am here because I just want to help others and to learn from others.

Author Comment

ID: 1405635
I listed just 3 unique examples of the conditions tht I encountered with this program.  I have actually run the program on more than 45 seperate computers and the trend is about the same.  I listed the more common machines.  I work in an area that has over 200 machines and have access to test it on any of them that I want to.
LVL 23

Expert Comment

ID: 1405636
So, have you tried the samples on any of the over 200 machines? If the samples work fine, you may look into them to figure out what the difference is.

I get the points only if the customers accept my answers. It is decided by the customers themselves rather than anybody else.

Author Comment

ID: 1405637
Yes, I had tried the samples and my program on the other machines. 45 of them.

It turns out that it's a problem in the bios as recoganized by Win95.  We went to my computer, Control Pannel, System, device manager, devices  and removed the associations for the system devices.  Rebooted the machine(s) that failed/gave unpredictable results and let Win95 rebuild the motherboard information and then the programs worked.
If you want I will accept your answer.
LVL 23

Accepted Solution

chensu earned 250 total points
ID: 1405638
Q: Why does this work differently on some machines?

A: There is something wrong with the machines not your code.

Q: How can I fix it???

A: You fixed it by yourself.

I still feel that this is one of my worst answers. Actually, what I provided is not an answer but a clue.

Thank you and happy programming.

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

With most software applications trying to cater to multiple user needs nowadays, the focus is to make them as configurable as possible. For e.g., when creating Silverlight applications which will connect to WCF services, the service end point usuall…
A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in an application. Themes can be made up of a set of elements: skins, style sheets, images, and o…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA.…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now