

Figure 4

//
// Source code for Command.NLM
//

#include <stdio.h>
#include <string.h>
#include <advanced.h>
#include <stdlib.h>
#include <process.h>
#include <debugapi.h>
#include <conio.h>
#include "command.h"

struct commandParserStructure parseStruct;
int myThreadGroupID;
int myScreenID;
int SystemScreenHandle;

int main(int argc, char **argv)
{
   int ccode = 0;

   argc = argc;
   argv = argv;

   // fill in resource tag and parseRoutine fields for command registration
   parseStruct.RTag = (struct ResourceTagStructure *)AllocateResourceTag(GetNLMHandle(), "Console 
Command Tag", ConsoleCommandSignature);
   parseStruct.parseRoutine = commandRoutine;

   // save off the current thread group and current screen
   myThreadGroupID = GetThreadGroupID();
   myScreenID = GetCurrentScreen();

   // try registering the command parser
   ccode = RegisterConsoleCommand(&parseStruct);

   if (!ccode)
   {
      // successful, print on our screen, then switch to console screen
      printf("Command Extension Loaded.\n");
      SystemScreenHandle = CreateScreen("System Console",0);
      DisplayScreen(SystemScreenHandle);

      // register unload function and leave code in memory
      AtUnload(commandUnload);
      ExitThread(TSR_THREAD,0);
   }
   else
      ConsolePrintf("Error %d, unable to register console command\n\n",ccode);

   return (ccode);
}

LONG commandRoutine(LONG screenID, BYTE* commandLine)
{
   LONG ccode;
   // Save off calling thread group
   int savedThreadGroupID = GetThreadGroupID();

   // turn off annoying warning
   screenID = screenID;

   // and set our thread group
   SetThreadGroupID(myThreadGroupID);

   // change default screen to console for the spawned NLM
   SetCurrentScreen(SystemScreenHandle);
   ccode = spawnlp(P_NOWAIT,commandLine,NULL);

   // change back to ours
   SetCurrentScreen(myScreenID);

   if (ccode == 0)
      printf("Executed Command \"%s\", ccode = %d\n",commandLine, ccode);
   else
      printf("Error Executing Command \"%s\", %s\n",commandLine, strerror(errno));

   // restore thread group
   SetThreadGroupID(savedThreadGroupID);
   return(0);
}


void commandUnload()
{
   // unregister the command parser, called at unload time
   UnRegisterConsoleCommand(&parseStruct);
}



