Main.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. //---------------------------------------------------------------------------
  2. #include <stdexcept>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <windows.h>
  6. #include "Console.h"
  7. #define MAX_ATTEMPTS 10
  8. //---------------------------------------------------------------------------
  9. using namespace std;
  10. HANDLE ConsoleInput = NULL;
  11. HANDLE Child = NULL;
  12. HANDLE CancelEvent = NULL;
  13. HANDLE InputTimerEvent = NULL;
  14. unsigned int OutputType = FILE_TYPE_UNKNOWN;
  15. unsigned int InputType = FILE_TYPE_UNKNOWN;
  16. enum { RESULT_GLOBAL_ERROR = 1, RESULT_INIT_ERROR = 2, RESULT_PROCESSING_ERROR = 3,
  17. RESULT_UNKNOWN_ERROR = 4 };
  18. const char * CONSOLE_CHILD_PARAM = "consolechild";
  19. //---------------------------------------------------------------------------
  20. inline TConsoleCommStruct* GetCommStruct(HANDLE FileMapping)
  21. {
  22. TConsoleCommStruct* Result;
  23. Result = static_cast<TConsoleCommStruct*>(MapViewOfFile(FileMapping,
  24. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  25. if (Result == NULL)
  26. {
  27. throw runtime_error("Cannot open mapping object.");
  28. }
  29. return Result;
  30. }
  31. //---------------------------------------------------------------------------
  32. inline void FreeCommStruct(TConsoleCommStruct* CommStruct)
  33. {
  34. UnmapViewOfFile(CommStruct);
  35. }
  36. //---------------------------------------------------------------------------
  37. void InitializeConsole(char* InstanceName, HANDLE& RequestEvent, HANDLE& ResponseEvent,
  38. HANDLE& CancelEvent, HANDLE& FileMapping, HANDLE& Job)
  39. {
  40. unsigned int Process = GetCurrentProcessId();
  41. int Attempts = 0;
  42. char Name[MAX_PATH];
  43. bool UniqEvent;
  44. do
  45. {
  46. if (Attempts > MAX_ATTEMPTS)
  47. {
  48. throw runtime_error("Cannot find unique name for event object.");
  49. }
  50. int InstanceNumber;
  51. #ifdef CONSOLE_TEST
  52. InstanceNumber = 1;
  53. #else
  54. InstanceNumber = random(1000);
  55. #endif
  56. sprintf(InstanceName, "_%u_%d", Process, InstanceNumber);
  57. sprintf(Name, "%s%s", CONSOLE_EVENT_REQUEST, InstanceName);
  58. HANDLE EventHandle = OpenEvent(EVENT_ALL_ACCESS, false, Name);
  59. UniqEvent = (EventHandle == NULL);
  60. if (!UniqEvent)
  61. {
  62. CloseHandle(EventHandle);
  63. }
  64. Attempts++;
  65. }
  66. while (!UniqEvent);
  67. RequestEvent = CreateEvent(NULL, false, false, Name);
  68. if (RequestEvent == NULL)
  69. {
  70. throw runtime_error("Cannot create request event object.");
  71. }
  72. sprintf(Name, "%s%s", CONSOLE_EVENT_RESPONSE, InstanceName);
  73. ResponseEvent = CreateEvent(NULL, false, false, Name);
  74. if (ResponseEvent == NULL)
  75. {
  76. throw runtime_error("Cannot create response event object.");
  77. }
  78. sprintf(Name, "%s%s", CONSOLE_EVENT_CANCEL, InstanceName);
  79. CancelEvent = CreateEvent(NULL, false, false, Name);
  80. if (CancelEvent == NULL)
  81. {
  82. throw runtime_error("Cannot create cancel event object.");
  83. }
  84. sprintf(Name, "%s%s", CONSOLE_MAPPING, InstanceName);
  85. FileMapping = CreateFileMapping((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  86. 0, sizeof(TConsoleCommStruct), Name);
  87. if (FileMapping == NULL)
  88. {
  89. throw runtime_error("Cannot create mapping object.");
  90. }
  91. typedef HANDLE WINAPI (*TCreateJobObject)(LPSECURITY_ATTRIBUTES JobAttributes, LPCTSTR Name);
  92. typedef HANDLE WINAPI (*TSetInformationJobObject)(HANDLE Job, JOBOBJECTINFOCLASS JobObjectInformationClass,
  93. LPVOID JobObjectInformation, DWORD JobObjectInformationLength);
  94. HANDLE Kernel32 = GetModuleHandle("kernel32");
  95. TCreateJobObject CreateJobObject =
  96. (TCreateJobObject)GetProcAddress(Kernel32, "CreateJobObjectA");
  97. TSetInformationJobObject SetInformationJobObject =
  98. (TSetInformationJobObject)GetProcAddress(Kernel32, "SetInformationJobObject");
  99. if ((CreateJobObject != NULL) && (SetInformationJobObject != NULL))
  100. {
  101. sprintf(Name, "%s%s", CONSOLE_JOB, InstanceName);
  102. Job = CreateJobObject(NULL, Name);
  103. if (Job == NULL)
  104. {
  105. throw runtime_error("Cannot create job object.");
  106. }
  107. JOBOBJECT_EXTENDED_LIMIT_INFORMATION ExtendedLimitInformation;
  108. memset(&ExtendedLimitInformation, 0, sizeof(ExtendedLimitInformation));
  109. ExtendedLimitInformation.BasicLimitInformation.LimitFlags =
  110. JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
  111. if (SetInformationJobObject(Job, JobObjectExtendedLimitInformation,
  112. &ExtendedLimitInformation, sizeof(ExtendedLimitInformation)) == 0)
  113. {
  114. CloseHandle(Job);
  115. Job = NULL;
  116. }
  117. }
  118. else
  119. {
  120. Job = NULL;
  121. }
  122. TConsoleCommStruct* CommStruct = GetCommStruct(FileMapping);
  123. CommStruct->Size = sizeof(TConsoleCommStruct);
  124. CommStruct->Version = TConsoleCommStruct::CurrentVersion;
  125. CommStruct->Event = TConsoleCommStruct::NONE;
  126. FreeCommStruct(CommStruct);
  127. }
  128. //---------------------------------------------------------------------------
  129. // duplicated in Common.cpp
  130. bool __fastcall CutToken(const char *& Str, char * Token)
  131. {
  132. bool Result;
  133. // inspired by Putty's sftp_getcmd() from PSFTP.C
  134. int Length = strlen(Str);
  135. int Index = 0;
  136. while ((Index < Length) &&
  137. ((Str[Index] == ' ') || (Str[Index] == '\t')))
  138. {
  139. Index++;
  140. }
  141. if (Index < Length)
  142. {
  143. bool Quoting = false;
  144. while (Index < Length)
  145. {
  146. if (!Quoting && ((Str[Index] == ' ') || (Str[Index] == '\t')))
  147. {
  148. break;
  149. }
  150. else if ((Str[Index] == '"') && (Index + 1 < Length) &&
  151. (Str[Index + 1] == '"'))
  152. {
  153. Index += 2;
  154. *Token = '"';
  155. Token++;
  156. }
  157. else if (Str[Index] == '"')
  158. {
  159. Index++;
  160. Quoting = !Quoting;
  161. }
  162. else
  163. {
  164. *Token = Str[Index];
  165. Token++;
  166. Index++;
  167. }
  168. }
  169. if (Index < Length)
  170. {
  171. Index++;
  172. }
  173. Str += Index;
  174. Result = true;
  175. }
  176. else
  177. {
  178. Result = false;
  179. Str += Length;
  180. }
  181. *Token = '\0';
  182. return Result;
  183. }
  184. //---------------------------------------------------------------------------
  185. void InitializeChild(const char* CommandLine, const char* InstanceName, HANDLE& Child)
  186. {
  187. int SkipParam = 0;
  188. char ChildPath[MAX_PATH] = "";
  189. size_t CommandLineLen = strlen(CommandLine);
  190. char* Buffer = new char[(CommandLineLen > MAX_PATH ? CommandLineLen : MAX_PATH) + 1];
  191. int Count = 0;
  192. const char * P = CommandLine;
  193. while (CutToken(P, Buffer))
  194. {
  195. if ((strchr("-/", Buffer[0]) != NULL) &&
  196. (strncmpi(Buffer + 1, CONSOLE_CHILD_PARAM, strlen(CONSOLE_CHILD_PARAM)) == 0) &&
  197. (Buffer[strlen(CONSOLE_CHILD_PARAM) + 1] == '='))
  198. {
  199. SkipParam = Count;
  200. strcpy(ChildPath, Buffer + 1 + strlen(CONSOLE_CHILD_PARAM) + 1);
  201. }
  202. ++Count;
  203. }
  204. if (strlen(ChildPath) == 0)
  205. {
  206. DWORD ModuleNameLen = GetModuleFileName(NULL, Buffer, MAX_PATH);
  207. if ((ModuleNameLen == 0) || (ModuleNameLen == MAX_PATH))
  208. {
  209. throw runtime_error("Error retrieving executable name.");
  210. }
  211. const char* LastDelimiter = strrchr(Buffer, '\\');
  212. const char* AppFileName;
  213. if (LastDelimiter != NULL)
  214. {
  215. strncpy(ChildPath, Buffer, LastDelimiter - Buffer + 1);
  216. ChildPath[LastDelimiter - Buffer + 1] = '\0';
  217. AppFileName = LastDelimiter + 1;
  218. }
  219. else
  220. {
  221. ChildPath[0] = '\0';
  222. AppFileName = Buffer;
  223. }
  224. const char* ExtensionStart = strrchr(AppFileName, '.');
  225. if (ExtensionStart != NULL)
  226. {
  227. char* End = ChildPath + strlen(ChildPath);
  228. strncpy(End, AppFileName, ExtensionStart - AppFileName);
  229. *(End + (ExtensionStart - AppFileName)) = '\0';
  230. }
  231. else
  232. {
  233. strcat(ChildPath, AppFileName);
  234. }
  235. strcat(ChildPath, ".exe");
  236. }
  237. char* Parameters = new char[(CommandLineLen * 2) + 100 + (Count * 3) + 1];
  238. sprintf(Parameters, "\"%s\" /console /consoleinstance=%s ", ChildPath, InstanceName);
  239. P = CommandLine;
  240. // skip executable path
  241. CutToken(P, Buffer);
  242. int i = 1;
  243. while (CutToken(P, Buffer))
  244. {
  245. if (i != SkipParam)
  246. {
  247. strcat(Parameters, "\"");
  248. char* P2 = Parameters + strlen(Parameters);
  249. const char* P3 = Buffer;
  250. const char* BufferEnd = Buffer + strlen(Buffer) + 1;
  251. while (P3 != BufferEnd)
  252. {
  253. *P2 = *P3;
  254. ++P2;
  255. if (*P3 == '"')
  256. {
  257. *P2 = '"';
  258. ++P2;
  259. }
  260. ++P3;
  261. }
  262. strcat(Parameters, "\" ");
  263. }
  264. ++i;
  265. }
  266. delete[] Buffer;
  267. STARTUPINFO StartupInfo = { sizeof(STARTUPINFO) };
  268. PROCESS_INFORMATION ProcessInfomation;
  269. BOOL Result =
  270. CreateProcess(ChildPath, Parameters, NULL, NULL, false, 0, NULL, NULL,
  271. &StartupInfo, &ProcessInfomation);
  272. delete[] Parameters;
  273. if (Result)
  274. {
  275. Child = ProcessInfomation.hProcess;
  276. }
  277. else
  278. {
  279. throw runtime_error("Cannot start WinSCP application.");
  280. }
  281. }
  282. //---------------------------------------------------------------------------
  283. void FinalizeChild(HANDLE Child)
  284. {
  285. if (Child != NULL)
  286. {
  287. TerminateProcess(Child, 0);
  288. CloseHandle(Child);
  289. }
  290. }
  291. //---------------------------------------------------------------------------
  292. void FinalizeConsole(const char* /*InstanceName*/, HANDLE RequestEvent,
  293. HANDLE ResponseEvent, HANDLE CancelEvent, HANDLE FileMapping, HANDLE Job)
  294. {
  295. CloseHandle(RequestEvent);
  296. CloseHandle(ResponseEvent);
  297. CloseHandle(CancelEvent);
  298. CloseHandle(FileMapping);
  299. CloseHandle(Job);
  300. }
  301. //---------------------------------------------------------------------------
  302. static char LastFromBeginning[sizeof(TConsoleCommStruct::TPrintEvent)] = "";
  303. //---------------------------------------------------------------------------
  304. inline void Flush()
  305. {
  306. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE))
  307. {
  308. fflush(stdout);
  309. }
  310. }
  311. //---------------------------------------------------------------------------
  312. void Print(bool FromBeginning, const char * Message)
  313. {
  314. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE))
  315. {
  316. if (FromBeginning && (Message[0] != '\n'))
  317. {
  318. strcpy(LastFromBeginning, Message);
  319. }
  320. else
  321. {
  322. if (LastFromBeginning[0] != '\0')
  323. {
  324. printf("%s", LastFromBeginning);
  325. LastFromBeginning[0] = '\0';
  326. }
  327. if (FromBeginning && (Message[0] == '\n'))
  328. {
  329. printf("\n");
  330. strcpy(LastFromBeginning, Message + 1);
  331. }
  332. else
  333. {
  334. printf("%s", Message);
  335. }
  336. Flush();
  337. }
  338. }
  339. else
  340. {
  341. if (FromBeginning)
  342. {
  343. printf("\r");
  344. }
  345. printf("%s", Message);
  346. }
  347. }
  348. //---------------------------------------------------------------------------
  349. inline void ProcessPrintEvent(TConsoleCommStruct::TPrintEvent& Event)
  350. {
  351. Print(Event.FromBeginning, Event.Message);
  352. }
  353. //---------------------------------------------------------------------------
  354. void BreakInput()
  355. {
  356. SetEvent(CancelEvent);
  357. }
  358. //---------------------------------------------------------------------------
  359. DWORD WINAPI InputTimerThreadProc(void * Parameter)
  360. {
  361. unsigned int Timer = reinterpret_cast<unsigned int>(Parameter);
  362. if (WaitForSingleObject(InputTimerEvent, Timer) == WAIT_TIMEOUT)
  363. {
  364. BreakInput();
  365. }
  366. return 0;
  367. }
  368. //---------------------------------------------------------------------------
  369. void ProcessInputEvent(TConsoleCommStruct::TInputEvent& Event)
  370. {
  371. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE))
  372. {
  373. unsigned long Len = 0;
  374. unsigned long Read;
  375. char Ch;
  376. bool Result;
  377. while (((Result = (ReadFile(ConsoleInput, &Ch, 1, &Read, NULL) != 0)) != false) &&
  378. (Read > 0) && (Len < sizeof(Event.Str) - 1) && (Ch != '\n'))
  379. {
  380. if (Ch != '\r')
  381. {
  382. Event.Str[Len] = Ch;
  383. Len++;
  384. }
  385. }
  386. Event.Str[Len] = '\0';
  387. Print(false, Event.Str);
  388. Print(false, "\n");
  389. Event.Result = ((Result && (Read > 0)) || (Len > 0));
  390. }
  391. else
  392. {
  393. unsigned long PrevMode, NewMode;
  394. GetConsoleMode(ConsoleInput, &PrevMode);
  395. NewMode = PrevMode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
  396. if (Event.Echo)
  397. {
  398. NewMode |= ENABLE_ECHO_INPUT;
  399. }
  400. else
  401. {
  402. NewMode &= ~ENABLE_ECHO_INPUT;
  403. }
  404. SetConsoleMode(ConsoleInput, NewMode);
  405. HANDLE InputTimerThread = NULL;
  406. try
  407. {
  408. if (Event.Timer > 0)
  409. {
  410. unsigned long ThreadId;
  411. InputTimerEvent = CreateEvent(NULL, false, false, NULL);
  412. InputTimerThread = CreateThread(NULL, 0, InputTimerThreadProc,
  413. reinterpret_cast<void *>(Event.Timer), 0, &ThreadId);
  414. }
  415. unsigned long Read;
  416. Event.Result = ReadConsole(ConsoleInput, Event.Str, sizeof(Event.Str) - 1, &Read, NULL);
  417. Event.Str[Read] = '\0';
  418. bool PendingCancel = (WaitForSingleObject(CancelEvent, 0) == WAIT_OBJECT_0);
  419. if (PendingCancel || !Event.Echo)
  420. {
  421. printf("\n");
  422. Flush();
  423. }
  424. if (PendingCancel || (Read == 0))
  425. {
  426. Event.Result = false;
  427. }
  428. }
  429. __finally
  430. {
  431. if (InputTimerThread != NULL)
  432. {
  433. SetEvent(InputTimerEvent);
  434. WaitForSingleObject(InputTimerThread, 100);
  435. CloseHandle(InputTimerEvent);
  436. InputTimerEvent = NULL;
  437. CloseHandle(InputTimerThread);
  438. }
  439. SetConsoleMode(ConsoleInput, PrevMode);
  440. }
  441. }
  442. }
  443. //---------------------------------------------------------------------------
  444. void ProcessChoiceEvent(TConsoleCommStruct::TChoiceEvent& Event)
  445. {
  446. // note that if output is redirected to file, input is still FILE_TYPE_CHAR
  447. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE))
  448. {
  449. Event.Result = Event.Cancel;
  450. }
  451. else
  452. {
  453. Event.Result = 0;
  454. unsigned long PrevMode, NewMode;
  455. GetConsoleMode(ConsoleInput, &PrevMode);
  456. NewMode = (PrevMode | ENABLE_PROCESSED_INPUT) & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  457. SetConsoleMode(ConsoleInput, NewMode);
  458. unsigned int ATimer = Event.Timer;
  459. try
  460. {
  461. do
  462. {
  463. unsigned long Read;
  464. INPUT_RECORD Record;
  465. if ((PeekConsoleInput(ConsoleInput, &Record, 1, &Read) != 0) &&
  466. (Read == 1))
  467. {
  468. if ((ReadConsoleInput(ConsoleInput, &Record, 1, &Read) != 0) &&
  469. (Read == 1))
  470. {
  471. bool PendingCancel = (WaitForSingleObject(CancelEvent, 0) == WAIT_OBJECT_0);
  472. if (PendingCancel)
  473. {
  474. Event.Result = Event.Break;
  475. }
  476. else if ((Record.EventType == KEY_EVENT) &&
  477. Record.Event.KeyEvent.bKeyDown)
  478. {
  479. char CStr[2];
  480. CStr[0] = Record.Event.KeyEvent.uChar.AsciiChar;
  481. CStr[1] = '\0';
  482. CharUpperBuff(CStr, 1);
  483. char C = CStr[0];
  484. if (C == 27)
  485. {
  486. Event.Result = Event.Cancel;
  487. }
  488. else if ((strchr(Event.Options, C) != NULL) &&
  489. ((Record.Event.KeyEvent.dwControlKeyState &
  490. (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED | LEFT_ALT_PRESSED |
  491. RIGHT_CTRL_PRESSED)) == 0))
  492. {
  493. Event.Result = strchr(Event.Options, C) - Event.Options + 1;
  494. }
  495. }
  496. }
  497. }
  498. if (Event.Result == 0)
  499. {
  500. unsigned int TimerSlice = 50;
  501. Sleep(TimerSlice);
  502. if (Event.Timer > 0)
  503. {
  504. if (ATimer > TimerSlice)
  505. {
  506. ATimer -= TimerSlice;
  507. }
  508. else
  509. {
  510. Event.Result = Event.Timeouted;
  511. }
  512. }
  513. }
  514. }
  515. while (Event.Result == 0);
  516. SetConsoleMode(ConsoleInput, PrevMode);
  517. }
  518. catch(...)
  519. {
  520. SetConsoleMode(ConsoleInput, PrevMode);
  521. throw;
  522. }
  523. }
  524. }
  525. //---------------------------------------------------------------------------
  526. inline void ProcessTitleEvent(TConsoleCommStruct::TTitleEvent& Event)
  527. {
  528. SetConsoleTitle(Event.Title);
  529. }
  530. //---------------------------------------------------------------------------
  531. inline void ProcessInitEvent(TConsoleCommStruct::TInitEvent& Event)
  532. {
  533. Event.InputType = InputType;
  534. Event.OutputType = OutputType;
  535. }
  536. //---------------------------------------------------------------------------
  537. void ProcessEvent(HANDLE ResponseEvent, HANDLE FileMapping)
  538. {
  539. TConsoleCommStruct* CommStruct = GetCommStruct(FileMapping);
  540. try
  541. {
  542. if (CommStruct->Version != TConsoleCommStruct::CurrentVersionConfirmed)
  543. {
  544. throw logic_error("Incompatible console protocol version");
  545. }
  546. switch (CommStruct->Event)
  547. {
  548. case TConsoleCommStruct::PRINT:
  549. ProcessPrintEvent(CommStruct->PrintEvent);
  550. break;
  551. case TConsoleCommStruct::INPUT:
  552. ProcessInputEvent(CommStruct->InputEvent);
  553. break;
  554. case TConsoleCommStruct::CHOICE:
  555. ProcessChoiceEvent(CommStruct->ChoiceEvent);
  556. break;
  557. case TConsoleCommStruct::TITLE:
  558. ProcessTitleEvent(CommStruct->TitleEvent);
  559. break;
  560. case TConsoleCommStruct::INIT:
  561. ProcessInitEvent(CommStruct->InitEvent);
  562. break;
  563. default:
  564. throw runtime_error("Unknown event");
  565. }
  566. FreeCommStruct(CommStruct);
  567. SetEvent(ResponseEvent);
  568. }
  569. catch(...)
  570. {
  571. FreeCommStruct(CommStruct);
  572. throw;
  573. }
  574. }
  575. //---------------------------------------------------------------------------
  576. BOOL WINAPI HandlerRoutine(DWORD CtrlType)
  577. {
  578. if ((CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_BREAK_EVENT))
  579. {
  580. BreakInput();
  581. return true;
  582. }
  583. else
  584. {
  585. FinalizeChild(Child);
  586. return false;
  587. }
  588. }
  589. //---------------------------------------------------------------------------
  590. #pragma argsused
  591. int main(int /*argc*/, char* /*argv*/[])
  592. {
  593. unsigned long Result = RESULT_UNKNOWN_ERROR;
  594. try
  595. {
  596. randomize();
  597. ConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
  598. InputType = GetFileType(ConsoleInput);
  599. SetConsoleCtrlHandler(HandlerRoutine, true);
  600. HANDLE ConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  601. OutputType = GetFileType(ConsoleOutput);
  602. char InstanceName[MAX_PATH];
  603. HANDLE RequestEvent, ResponseEvent, FileMapping, Job;
  604. InitializeConsole(InstanceName, RequestEvent, ResponseEvent,
  605. CancelEvent, FileMapping, Job);
  606. char SavedTitle[512];
  607. GetConsoleTitle(SavedTitle, sizeof(SavedTitle));
  608. try
  609. {
  610. #ifndef CONSOLE_TEST
  611. InitializeChild(GetCommandLine(), InstanceName, Child);
  612. #endif
  613. try
  614. {
  615. bool Continue = true;
  616. do
  617. {
  618. HANDLE Handles[2];
  619. Handles[0] = RequestEvent;
  620. Handles[1] = Child;
  621. unsigned int HandleCount;
  622. #ifndef CONSOLE_TEST
  623. HandleCount = 2;
  624. #else
  625. HandleCount = 1;
  626. #endif
  627. unsigned long WaitResult =
  628. WaitForMultipleObjects(HandleCount, Handles, false, INFINITE);
  629. switch (WaitResult)
  630. {
  631. case WAIT_OBJECT_0:
  632. ProcessEvent(ResponseEvent, FileMapping);
  633. break;
  634. case WAIT_OBJECT_0 + 1:
  635. GetExitCodeProcess(Child, &Result);
  636. CloseHandle(Child);
  637. Child = NULL;
  638. Continue = false;
  639. break;
  640. default:
  641. throw runtime_error("Error waiting for communication from child process.");
  642. }
  643. }
  644. while (Continue);
  645. // flush pending progress message
  646. Print(false, "");
  647. }
  648. catch(const exception& e)
  649. {
  650. puts(e.what());
  651. Result = RESULT_PROCESSING_ERROR;
  652. }
  653. #ifndef CONSOLE_TEST
  654. FinalizeChild(Child);
  655. #endif
  656. SetConsoleTitle(SavedTitle);
  657. }
  658. catch(const exception& e)
  659. {
  660. puts(e.what());
  661. Result = RESULT_INIT_ERROR;
  662. }
  663. FinalizeConsole(InstanceName, RequestEvent, ResponseEvent,
  664. CancelEvent, FileMapping, Job);
  665. }
  666. catch(const exception& e)
  667. {
  668. puts(e.what());
  669. Result = RESULT_GLOBAL_ERROR;
  670. }
  671. return Result;
  672. }
  673. //---------------------------------------------------------------------------