ctkErrorLogFDMessageHandler.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0.txt
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QDebug>
  16. #include <QFile>
  17. // CTK includes
  18. #include "ctkErrorLogContext.h"
  19. #include "ctkErrorLogFDMessageHandler.h"
  20. #include "ctkErrorLogFDMessageHandler_p.h"
  21. #include "ctkUtils.h"
  22. // STD includes
  23. #include <cstdio>
  24. #ifdef Q_OS_WIN32
  25. # include <fcntl.h> // For _O_TEXT
  26. # include <io.h> // For _pipe, _dup and _dup2
  27. #else
  28. # include <unistd.h> // For pipe, dup and dup2
  29. #endif
  30. // --------------------------------------------------------------------------
  31. // ctkFDHandler methods
  32. // See http://stackoverflow.com/questions/5419356/redirect-stdout-stderr-to-a-string
  33. // and http://stackoverflow.com/questions/955962/how-to-buffer-stdout-in-memory-and-write-it-from-a-dedicated-thread
  34. // --------------------------------------------------------------------------
  35. ctkFDHandler::ctkFDHandler(ctkErrorLogFDMessageHandler* messageHandler,
  36. ctkErrorLogLevel::LogLevel logLevel,
  37. ctkErrorLogTerminalOutput::TerminalOutput terminalOutput)
  38. {
  39. this->MessageHandler = messageHandler;
  40. this->LogLevel = logLevel;
  41. this->TerminalOutput = terminalOutput;
  42. this->SavedFDNumber = 0;
  43. this->Enabled = false;
  44. }
  45. // --------------------------------------------------------------------------
  46. ctkFDHandler::~ctkFDHandler()
  47. {
  48. }
  49. // --------------------------------------------------------------------------
  50. void ctkFDHandler::setupPipe()
  51. {
  52. #ifdef Q_OS_WIN32
  53. int status = _pipe(this->Pipe, 65536, _O_TEXT);
  54. #else
  55. int status = pipe(this->Pipe);
  56. #endif
  57. if (status != 0)
  58. {
  59. qCritical().nospace() << "ctkFDHandler - Failed to create pipe !";
  60. return;
  61. }
  62. }
  63. // --------------------------------------------------------------------------
  64. FILE* ctkFDHandler::terminalOutputFile()
  65. {
  66. return this->TerminalOutput == ctkErrorLogTerminalOutput::StandardOutput ? stdout : stderr;
  67. }
  68. // --------------------------------------------------------------------------
  69. void ctkFDHandler::setEnabled(bool value)
  70. {
  71. if (this->Enabled == value)
  72. {
  73. return;
  74. }
  75. if (value)
  76. {
  77. this->setupPipe();
  78. // Flush (stdout|stderr) so that any buffered messages are delivered
  79. fflush(this->terminalOutputFile());
  80. // Save position of current standard output
  81. fgetpos(this->terminalOutputFile(), &this->SavedFDPos);
  82. #ifdef Q_OS_WIN32
  83. this->SavedFDNumber = _dup(_fileno(this->terminalOutputFile()));
  84. _dup2(this->Pipe[1], _fileno(this->terminalOutputFile()));
  85. _close(this->Pipe[1]);
  86. #else
  87. this->SavedFDNumber = dup(fileno(this->terminalOutputFile()));
  88. dup2(this->Pipe[1], fileno(this->terminalOutputFile()));
  89. close(this->Pipe[1]);
  90. #endif
  91. // Start polling thread
  92. this->Enabled = true;
  93. this->start();
  94. }
  95. else
  96. {
  97. // Print one character to "unblock" the read function associated with the polling thread
  98. #ifdef Q_OS_WIN32
  99. _write(_fileno(this->terminalOutputFile()), "\n", 1);
  100. #else
  101. write(fileno(this->terminalOutputFile()), "\n", 1);
  102. #endif
  103. // Flush stdout or stderr so that any buffered messages are delivered
  104. fflush(this->terminalOutputFile());
  105. // Stop polling thread
  106. {
  107. QMutexLocker locker(&this->EnableMutex);
  108. this->Enabled = false;
  109. }
  110. QString newline("\n");
  111. #ifdef Q_OS_WIN32
  112. _write(_fileno(this->terminalOutputFile()), qPrintable(newline), newline.size());
  113. #else
  114. write(fileno(this->terminalOutputFile()), qPrintable(newline), newline.size());
  115. #endif
  116. // Wait the polling thread graciously terminates
  117. this->wait();
  118. // Close files and restore standard output to stdout or stderr - which should be the terminal
  119. #ifdef Q_OS_WIN32
  120. _dup2(this->SavedFDNumber, _fileno(this->terminalOutputFile()));
  121. _close(this->SavedFDNumber);
  122. #else
  123. dup2(this->SavedFDNumber, fileno(this->terminalOutputFile()));
  124. close(this->SavedFDNumber);
  125. #endif
  126. clearerr(this->terminalOutputFile());
  127. fsetpos(this->terminalOutputFile(), &this->SavedFDPos);
  128. #ifdef Q_OS_WIN32
  129. _close(this->Pipe[0]);
  130. #else
  131. close(this->Pipe[0]);
  132. #endif
  133. this->SavedFDNumber = 0;
  134. }
  135. ctkErrorLogTerminalOutput * terminalOutput =
  136. this->MessageHandler->terminalOutput(this->TerminalOutput);
  137. if(terminalOutput)
  138. {
  139. terminalOutput->setFileDescriptor(this->SavedFDNumber);
  140. }
  141. }
  142. // --------------------------------------------------------------------------
  143. bool ctkFDHandler::enabled()const
  144. {
  145. QMutexLocker locker(&this->EnableMutex);
  146. return this->Enabled;
  147. }
  148. // --------------------------------------------------------------------------
  149. void ctkFDHandler::run()
  150. {
  151. while(true)
  152. {
  153. char c = '\0';
  154. QString line;
  155. while(c != '\n')
  156. {
  157. #ifdef Q_OS_WIN32
  158. int res = _read(this->Pipe[0], &c, 1); // When used with pipe, read() is blocking
  159. #else
  160. ssize_t res = read(this->Pipe[0], &c, 1); // When used with pipe, read() is blocking
  161. #endif
  162. if (res == -1)
  163. {
  164. break;
  165. }
  166. if (c != '\n')
  167. {
  168. line += c;
  169. }
  170. }
  171. if (!this->enabled())
  172. {
  173. break;
  174. }
  175. Q_ASSERT(this->MessageHandler);
  176. this->MessageHandler->handleMessage(
  177. ctk::qtHandleToString(QThread::currentThreadId()),
  178. this->LogLevel,
  179. this->MessageHandler->handlerPrettyName(),
  180. ctkErrorLogContext(line),
  181. line);
  182. }
  183. }
  184. // --------------------------------------------------------------------------
  185. // ctkErrorLogFDMessageHandlerPrivate
  186. // --------------------------------------------------------------------------
  187. class ctkErrorLogFDMessageHandlerPrivate
  188. {
  189. public:
  190. ctkErrorLogFDMessageHandlerPrivate();
  191. ~ctkErrorLogFDMessageHandlerPrivate();
  192. ctkFDHandler * StdOutFDHandler;
  193. ctkFDHandler * StdErrFDHandler;
  194. };
  195. // --------------------------------------------------------------------------
  196. // ctkErrorLogFDMessageHandlerPrivate methods
  197. //------------------------------------------------------------------------------
  198. ctkErrorLogFDMessageHandlerPrivate::ctkErrorLogFDMessageHandlerPrivate()
  199. {
  200. }
  201. //------------------------------------------------------------------------------
  202. ctkErrorLogFDMessageHandlerPrivate::~ctkErrorLogFDMessageHandlerPrivate()
  203. {
  204. delete this->StdOutFDHandler;
  205. delete this->StdErrFDHandler;
  206. }
  207. //------------------------------------------------------------------------------
  208. // ctkErrorLogFDMessageHandler methods
  209. //------------------------------------------------------------------------------
  210. QString ctkErrorLogFDMessageHandler::HandlerName = QLatin1String("FD");
  211. // --------------------------------------------------------------------------
  212. ctkErrorLogFDMessageHandler::ctkErrorLogFDMessageHandler() :
  213. Superclass(), d_ptr(new ctkErrorLogFDMessageHandlerPrivate())
  214. {
  215. Q_D(ctkErrorLogFDMessageHandler);
  216. d->StdOutFDHandler = new ctkFDHandler(this, ctkErrorLogLevel::Info, ctkErrorLogTerminalOutput::StandardOutput);
  217. d->StdErrFDHandler = new ctkFDHandler(this, ctkErrorLogLevel::Critical, ctkErrorLogTerminalOutput::StandardError);
  218. }
  219. // --------------------------------------------------------------------------
  220. ctkErrorLogFDMessageHandler::~ctkErrorLogFDMessageHandler()
  221. {
  222. }
  223. // --------------------------------------------------------------------------
  224. QString ctkErrorLogFDMessageHandler::handlerName()const
  225. {
  226. return ctkErrorLogFDMessageHandler::HandlerName;
  227. }
  228. // --------------------------------------------------------------------------
  229. void ctkErrorLogFDMessageHandler::setEnabledInternal(bool value)
  230. {
  231. Q_D(ctkErrorLogFDMessageHandler);
  232. d->StdOutFDHandler->setEnabled(value);
  233. d->StdErrFDHandler->setEnabled(value);
  234. }