ctkErrorLogFDMessageHandler.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. int unused = _write(_fileno(this->terminalOutputFile()), "\n", 1);
  100. #else
  101. ssize_t unused = write(fileno(this->terminalOutputFile()), "\n", 1);
  102. #endif
  103. Q_UNUSED(unused);
  104. // Flush stdout or stderr so that any buffered messages are delivered
  105. fflush(this->terminalOutputFile());
  106. // Stop polling thread
  107. {
  108. QMutexLocker locker(&this->EnableMutex);
  109. this->Enabled = false;
  110. }
  111. QString newline("\n");
  112. #ifdef Q_OS_WIN32
  113. unused = _write(_fileno(this->terminalOutputFile()), qPrintable(newline), newline.size());
  114. #else
  115. unused = write(fileno(this->terminalOutputFile()), qPrintable(newline), newline.size());
  116. #endif
  117. Q_UNUSED(unused);
  118. // Wait the polling thread graciously terminates
  119. this->wait();
  120. // Close files and restore standard output to stdout or stderr - which should be the terminal
  121. #ifdef Q_OS_WIN32
  122. _dup2(this->SavedFDNumber, _fileno(this->terminalOutputFile()));
  123. _close(this->SavedFDNumber);
  124. #else
  125. dup2(this->SavedFDNumber, fileno(this->terminalOutputFile()));
  126. close(this->SavedFDNumber);
  127. #endif
  128. clearerr(this->terminalOutputFile());
  129. fsetpos(this->terminalOutputFile(), &this->SavedFDPos);
  130. #ifdef Q_OS_WIN32
  131. _close(this->Pipe[0]);
  132. #else
  133. close(this->Pipe[0]);
  134. #endif
  135. this->SavedFDNumber = 0;
  136. }
  137. ctkErrorLogTerminalOutput * terminalOutput =
  138. this->MessageHandler->terminalOutput(this->TerminalOutput);
  139. if(terminalOutput)
  140. {
  141. terminalOutput->setFileDescriptor(this->SavedFDNumber);
  142. }
  143. }
  144. // --------------------------------------------------------------------------
  145. bool ctkFDHandler::enabled()const
  146. {
  147. QMutexLocker locker(&this->EnableMutex);
  148. return this->Enabled;
  149. }
  150. // --------------------------------------------------------------------------
  151. void ctkFDHandler::run()
  152. {
  153. while(true)
  154. {
  155. char c = '\0';
  156. QString line;
  157. while(c != '\n')
  158. {
  159. #ifdef Q_OS_WIN32
  160. int res = _read(this->Pipe[0], &c, 1); // When used with pipe, read() is blocking
  161. #else
  162. ssize_t res = read(this->Pipe[0], &c, 1); // When used with pipe, read() is blocking
  163. #endif
  164. if (res == -1)
  165. {
  166. break;
  167. }
  168. if (c != '\n')
  169. {
  170. line += c;
  171. }
  172. }
  173. if (!this->enabled())
  174. {
  175. break;
  176. }
  177. Q_ASSERT(this->MessageHandler);
  178. this->MessageHandler->handleMessage(
  179. ctk::qtHandleToString(QThread::currentThreadId()),
  180. this->LogLevel,
  181. this->MessageHandler->handlerPrettyName(),
  182. ctkErrorLogContext(line),
  183. line);
  184. }
  185. }
  186. // --------------------------------------------------------------------------
  187. // ctkErrorLogFDMessageHandlerPrivate
  188. // --------------------------------------------------------------------------
  189. class ctkErrorLogFDMessageHandlerPrivate
  190. {
  191. public:
  192. ctkErrorLogFDMessageHandlerPrivate();
  193. ~ctkErrorLogFDMessageHandlerPrivate();
  194. ctkFDHandler * StdOutFDHandler;
  195. ctkFDHandler * StdErrFDHandler;
  196. };
  197. // --------------------------------------------------------------------------
  198. // ctkErrorLogFDMessageHandlerPrivate methods
  199. //------------------------------------------------------------------------------
  200. ctkErrorLogFDMessageHandlerPrivate::ctkErrorLogFDMessageHandlerPrivate()
  201. {
  202. }
  203. //------------------------------------------------------------------------------
  204. ctkErrorLogFDMessageHandlerPrivate::~ctkErrorLogFDMessageHandlerPrivate()
  205. {
  206. delete this->StdOutFDHandler;
  207. delete this->StdErrFDHandler;
  208. }
  209. //------------------------------------------------------------------------------
  210. // ctkErrorLogFDMessageHandler methods
  211. //------------------------------------------------------------------------------
  212. QString ctkErrorLogFDMessageHandler::HandlerName = QLatin1String("FD");
  213. // --------------------------------------------------------------------------
  214. ctkErrorLogFDMessageHandler::ctkErrorLogFDMessageHandler() :
  215. Superclass(), d_ptr(new ctkErrorLogFDMessageHandlerPrivate())
  216. {
  217. Q_D(ctkErrorLogFDMessageHandler);
  218. d->StdOutFDHandler = new ctkFDHandler(this, ctkErrorLogLevel::Info, ctkErrorLogTerminalOutput::StandardOutput);
  219. d->StdErrFDHandler = new ctkFDHandler(this, ctkErrorLogLevel::Critical, ctkErrorLogTerminalOutput::StandardError);
  220. }
  221. // --------------------------------------------------------------------------
  222. ctkErrorLogFDMessageHandler::~ctkErrorLogFDMessageHandler()
  223. {
  224. }
  225. // --------------------------------------------------------------------------
  226. QString ctkErrorLogFDMessageHandler::handlerName()const
  227. {
  228. return ctkErrorLogFDMessageHandler::HandlerName;
  229. }
  230. // --------------------------------------------------------------------------
  231. void ctkErrorLogFDMessageHandler::setEnabledInternal(bool value)
  232. {
  233. Q_D(ctkErrorLogFDMessageHandler);
  234. d->StdOutFDHandler->setEnabled(value);
  235. d->StdErrFDHandler->setEnabled(value);
  236. }