Main.cpp 20 KB

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