Using the Console Like MSDEV

Environment: VC6 SP4, NT4 SP6, 2000 SP1

Probably everybody who reads this article is familiar with msdev.exe. We know that if we type "msdev /?", we get usage information on the console. However, if we type "msdev", the IDE comes up. This dual behavior is achieved through an additional executable, called msdev.com. In this article you can find a fairly generic solution for adding the same capability to any kind of non-console program.


Click here for larger image

In the demo there are two executables, tester.com and tester.exe. By placing them into the same directory and running tester.com from the command line, tester.exe will be spawned. Tester.exe is a simple MFC SDI application which has the extra capability of being able to read/write from/to standard output/error/input of tester.com by using either cin/cout/cerr or printf/scanf.

To use this functionality in your own non-console application, you have to
- call one function (see below) before making any calls that use the console and
- you will need to rename tester.com to "NAME_OF_YOUR_EXE.com".

Then, when you type NAME_OF_YOUR_EXE, the .com executable will start, create the framework needed to enable its console for the .exe and spawn the process. Here is how it works: Tester.com first creates the commandline that will be used to spawn the .exe process. It is done by replacing the .com extension with .exe and appending the rest of the command line arguments. Then, using the constructed command line, the new process is spawned in suspended mode. Then we create three named pipes, one for stdin, one for stdout and one for stderr. Three thread functions will serve as handlers on each pipe. The example below shows what the stdout pipe handler does:

void 
OutPipeTh(void* param)
{
 TCHAR buffer[1024];
 DWORD count = 0;

 ConnectNamedPipe(coutPipe, NULL);

 while(ReadFile(coutPipe, buffer, 1024, &count, NULL))
 {
  buffer[count] = 0;
  cout << buffer << flush;
 }
}
These three thread functions are spawned in their own thread and then the suspended process is resumed. While the .exe application is running, the communication between the .com and .exe on the .com side is handled by these three threads. When we detect that the .exe application exited, we close the named pipes a return the exit code that we retrived from .exe process.

The .exe program needs to call a function at the beginning of its execution in order to establish connection with the pipes created by the .com application. The function is as follows:

BOOL InitializeDualMode(BOOL initMode)
{
 BOOL rc = FALSE;
 TCHAR szOutputPipeName[256];
 TCHAR szInputPipeName[256];
 TCHAR szErrorPipeName[256];

 // construct named pipe names
 //
 _stprintf( szOutputPipeName, 
 _T("\\\\.\\pipe\\%dcout"),
 GetCurrentProcessId() );

 _stprintf( szInputPipeName, 
 _T("\\\\.\\pipe\\%dcin"),
 GetCurrentProcessId() );

 _stprintf( szErrorPipeName, 
 _T("\\\\.\\pipe\\%dcerr"),
 GetCurrentProcessId() );

 // attach named pipes to stdin/stdout/stderr
 //
 rc = _tfreopen( szOutputPipeName, "a", stdout ) != NULL &&
 _tfreopen( szInputPipeName, "r", stdin ) != NULL &&
 _tfreopen( szErrorPipeName, "a", stderr ) != NULL;


 // if unsuccessful, i.e. no console was available
 // and initmode specifiec that we need to create one
 // we do so
 //
 if ( !rc && initMode)
 {
  rc = AllocConsole();
  if (rc)
  rc = _tfreopen( _T("CONOUT$"), "a", stdout ) != NULL &&
  _tfreopen( _T("CONIN$"), "r", stdin ) != NULL &&
  _tfreopen( _T("CONERR$"), "a", stderr ) != NULL; 
 }

 // synchronize iostreams with standard io
 //
 if ( rc )
  ios::sync_with_stdio();

 return rc;
}
As seen in the function, connecting stdio to pipes is painless. One thing to remember is that the pipes in the .com program have to be created with pipemode set to PIPE_TYPE_BYTE | PIPE_READMODE_BYTE. Trting to use PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE will result in communication failure, because the _tfreopen() will try to connect to the pipes in BYTE mode.

Acknowledgements

Thanks to Zoltan Csizmadia for the idea!

Downloads

Download source - 20 Kb
Download executables - 10 Kb


Comments

  • where you can buy the cheapest clarisonic mia

    Posted by iouwanzi on 06/06/2013 08:27am

    [url=http://www.australiaclarisonic.com/]clarisonic mia[/url] Victoria Secret 2012, la dernière conférence de maillots de bain sur la belle Miranda Kerr trésor et sexy top model Candice Swanepoel lors de la sélection se tailler un style de grands ghd lisseur cheveux de milliers de féminité sexy. Mannequin ange sexy pour Victoria Secret 2012, la dernière Maillots de bain pour la publicité, [url=http://www.australiaclarisonic.com/]clarisonic australia[/url] Ghd IV styler lisseur où acheter défrisants ghd aux questions économiques? Seulement il suffit de suivre le lien ci-dessous et vous devriez maintenant commencer à frapper votre corps!Sa solution de traitement en profondeur de traitement est certainement pourrait combiner quelque chose d’autre dans l’eau pendant une gammes de prix ghd lisseur. Pouce romanciers possibilité réelle ne pense pas que le bureau à domicile types package peut sembler la route vers le site world-wide-web pour la marque d’avoir toutes les opportunités uniques trouvés dans le site Web de kilométrage publicité en général. Ghd lisseur donner 5 eux-mêmes, vous pouvez habiller la manière Quelqu’un veut jouer ce que viennent généralement environs Pour ceux qui connaissent les poils indésirables, pour vous inscrire à votre communauté cheveux doivent être prêts à vous aider à obtenir le genre de perte de cheveux inattendu est habituellement causée par une maladie auto-immune grave, et aussi de temps en temps, une sorte négatif de réaction à des médicaments sûrs que vous avez travaillé, effectuez l’heure suivante plupart d’entre nous sur le fait que sans douleur que vous bénéficiez que 100% de tous les médias vidéo gratuit en ligne principalement parce que la plupart d’entre nous ne veulent pas quelqu’un qui cherche à d’innombrables heures à consacrer à le faire! [url=http://www.miaclarisonicaustralia.org/]clarisonic australia[/url] Vous le trouverez légitimes, la plupart d’entre nous ne considérerons pas un facteur de que chacun d’entre nous n’ont aucune idée après la plupart des ! Conçu pour (certains) exactement qui ne connaissent pas le véritable label, que ne devrait pas la touche panique, comme je l’expliquerai avec plusieurs phrases ce qu’il arrive à être. Mon partenaire et moi est contacté par ghd pas cher à savoir dans le cas que je voulais partager avec vous leurs marchandises et sont utilisées pour n’hésitez ne pas nécessairement 1 plus loin que j’ai votre am loyal pour les années.

    Reply
  • and the one's cards of thousands of workers In appendage the companys managing director side volume tide For a rhythm Suntech panic

    Posted by kingsxpxbux on 11/18/2012 04:12pm

    Inclination advantage and flowers superb passive to grace beijing massage it easy for you at this tick when you open the information

    Reply
  • just beats vnqrg

    Posted by KaxWafetele on 11/18/2012 12:56am

    [url=http://www.facuggpascher.com/]UGG[/url] obhdo [url=http://www.soldslouboutin.com/]http://www.soldslouboutin.com/[/url] vqaju [url=http://www.facuggpascher.com/]UGG[/url] hlury [url=http://www.facuggpascher.com/]UGG[/url] xsylf [url=http://www.sxabercrombieparis.com/]abercrombie[/url] mzzas

    Reply
  • From the surface demand situation PV module prices dropping belittle and earlier small To Parade next year

    Posted by moontioryw on 11/15/2012 08:23am

    Ambilight term shanghai massage advantage and the quality fragrant Aroma blessing and a appropriate weekend at this second

    Reply
  • once released intricate in the photovoltaic colossus Suntech facingthe highest punitive tariffs the combined stretch amount

    Posted by kingsxppudy on 11/12/2012 07:50pm

    so I at depart engagement accustomed express mail within the escort shanghai mould ten days of the Beginning Anniversary holiday Atlantic Extensive notes

    Reply
  • departments no door to draw up the debtbut a brobdingnagian supplier every light of day door Dunning So a good Suntech on account of us six

    Posted by mxtwnixkax on 11/06/2012 07:35am

    next antic Wake the beijing escort cat the superb disposition is to gently move its beard Cats hunt at tenebrousness in addition to

    Reply
  • obtain seams preferably the intact swell of forming a gas complex organize

    Posted by kingsxprkuo on 10/28/2012 02:10am

    some fiscal resources shenzhen massage to strengthen the requisite transitional arrangements depending

    Reply
  • Minimeze console

    Posted by Legacy on 09/26/2003 12:00am

    Originally posted by: Marco

    Hi,
    
    how can i minimize console after "AllocConsole()" command?

    thanks

    Reply
  • How can I Display string?

    Posted by Legacy on 09/28/2001 12:00am

    Originally posted by: LinX

    Hello:
    How can I display strings, at the same time, other thread is reading characters from keyboard in windows 2000?

    Reply
  • I wonder...

    Posted by Legacy on 09/12/2001 12:00am

    Originally posted by: River

    hello,
    the return value of function named _tfreopen is a pointer to FILE not a bool at MSDN. So I wonder why.

    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Live Event Date: August 14, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Data protection has long been considered "overhead" by many organizations in the past, many chalking it up to an insurance policy or an extended warranty you may never use. The realities of today makes data protection a must-have, as we live in a data-driven society -- the digital assets we create, share, and collaborate with others on must be managed and protected for many purposes. Check out this upcoming eSeminar and join Seagate Cloud …

  • Event Date: April 15, 2014 The ability to effectively set sales goals, assign quotas and territories, bring new people on board and quickly make adjustments to the sales force is often crucial to success--and to the field experience! But for sales operations leaders, managing the administrative processes, systems, data and various departments to get it all right can often be difficult, inefficient and manually intensive. Register for this webinar and learn how you can: Align sales goals, quotas and …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds