juce_ConnectedChildProcess.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. enum { magicMastSlaveConnectionHeader = 0x712baf04 };
  20. static const char* startMessage = "__ipc_st";
  21. static const char* killMessage = "__ipc_k_";
  22. static const char* pingMessage = "__ipc_p_";
  23. enum { specialMessageSize = 8, defaultTimeoutMs = 8000 };
  24. static inline bool isMessageType (const MemoryBlock& mb, const char* messageType) noexcept
  25. {
  26. return mb.matches (messageType, (size_t) specialMessageSize);
  27. }
  28. static String getCommandLinePrefix (const String& commandLineUniqueID)
  29. {
  30. return "--" + commandLineUniqueID + ":";
  31. }
  32. //==============================================================================
  33. // This thread sends and receives ping messages every second, so that it
  34. // can find out if the other process has stopped running.
  35. struct ChildProcessPingThread : public Thread,
  36. private AsyncUpdater
  37. {
  38. ChildProcessPingThread (int timeout) : Thread ("IPC ping"), timeoutMs (timeout)
  39. {
  40. pingReceived();
  41. }
  42. void pingReceived() noexcept { countdown = timeoutMs / 1000 + 1; }
  43. void triggerConnectionLostMessage() { triggerAsyncUpdate(); }
  44. virtual bool sendPingMessage (const MemoryBlock&) = 0;
  45. virtual void pingFailed() = 0;
  46. int timeoutMs;
  47. private:
  48. Atomic<int> countdown;
  49. void handleAsyncUpdate() override { pingFailed(); }
  50. void run() override
  51. {
  52. while (! threadShouldExit())
  53. {
  54. if (--countdown <= 0 || ! sendPingMessage ({ pingMessage, specialMessageSize }))
  55. {
  56. triggerConnectionLostMessage();
  57. break;
  58. }
  59. wait (1000);
  60. }
  61. }
  62. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcessPingThread)
  63. };
  64. //==============================================================================
  65. struct ChildProcessMaster::Connection : public InterprocessConnection,
  66. private ChildProcessPingThread
  67. {
  68. Connection (ChildProcessMaster& m, const String& pipeName, int timeout)
  69. : InterprocessConnection (false, magicMastSlaveConnectionHeader),
  70. ChildProcessPingThread (timeout),
  71. owner (m)
  72. {
  73. if (createPipe (pipeName, timeoutMs))
  74. startThread (4);
  75. }
  76. ~Connection() override
  77. {
  78. stopThread (10000);
  79. }
  80. private:
  81. void connectionMade() override {}
  82. void connectionLost() override { owner.handleConnectionLost(); }
  83. bool sendPingMessage (const MemoryBlock& m) override { return owner.sendMessageToSlave (m); }
  84. void pingFailed() override { connectionLost(); }
  85. void messageReceived (const MemoryBlock& m) override
  86. {
  87. pingReceived();
  88. if (m.getSize() != specialMessageSize || ! isMessageType (m, pingMessage))
  89. owner.handleMessageFromSlave (m);
  90. }
  91. ChildProcessMaster& owner;
  92. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Connection)
  93. };
  94. //==============================================================================
  95. ChildProcessMaster::ChildProcessMaster() {}
  96. ChildProcessMaster::~ChildProcessMaster()
  97. {
  98. killSlaveProcess();
  99. }
  100. void ChildProcessMaster::handleConnectionLost() {}
  101. bool ChildProcessMaster::sendMessageToSlave (const MemoryBlock& mb)
  102. {
  103. if (connection != nullptr)
  104. return connection->sendMessage (mb);
  105. jassertfalse; // this can only be used when the connection is active!
  106. return false;
  107. }
  108. bool ChildProcessMaster::launchSlaveProcess (const File& executable, const String& commandLineUniqueID,
  109. int timeoutMs, int streamFlags)
  110. {
  111. killSlaveProcess();
  112. auto pipeName = "p" + String::toHexString (Random().nextInt64());
  113. StringArray args;
  114. args.add (executable.getFullPathName());
  115. args.add (getCommandLinePrefix (commandLineUniqueID) + pipeName);
  116. childProcess.reset (new ChildProcess());
  117. if (childProcess->start (args, streamFlags))
  118. {
  119. connection.reset (new Connection (*this, pipeName, timeoutMs <= 0 ? defaultTimeoutMs : timeoutMs));
  120. if (connection->isConnected())
  121. {
  122. sendMessageToSlave ({ startMessage, specialMessageSize });
  123. return true;
  124. }
  125. connection.reset();
  126. }
  127. return false;
  128. }
  129. void ChildProcessMaster::killSlaveProcess()
  130. {
  131. if (connection != nullptr)
  132. {
  133. sendMessageToSlave ({ killMessage, specialMessageSize });
  134. connection->disconnect();
  135. connection.reset();
  136. }
  137. childProcess.reset();
  138. }
  139. //==============================================================================
  140. struct ChildProcessSlave::Connection : public InterprocessConnection,
  141. private ChildProcessPingThread
  142. {
  143. Connection (ChildProcessSlave& p, const String& pipeName, int timeout)
  144. : InterprocessConnection (false, magicMastSlaveConnectionHeader),
  145. ChildProcessPingThread (timeout),
  146. owner (p)
  147. {
  148. connectToPipe (pipeName, timeoutMs);
  149. startThread (4);
  150. }
  151. ~Connection() override
  152. {
  153. stopThread (10000);
  154. }
  155. private:
  156. ChildProcessSlave& owner;
  157. void connectionMade() override {}
  158. void connectionLost() override { owner.handleConnectionLost(); }
  159. bool sendPingMessage (const MemoryBlock& m) override { return owner.sendMessageToMaster (m); }
  160. void pingFailed() override { connectionLost(); }
  161. void messageReceived (const MemoryBlock& m) override
  162. {
  163. pingReceived();
  164. if (isMessageType (m, pingMessage))
  165. return;
  166. if (isMessageType (m, killMessage))
  167. return triggerConnectionLostMessage();
  168. if (isMessageType (m, startMessage))
  169. return owner.handleConnectionMade();
  170. owner.handleMessageFromMaster (m);
  171. }
  172. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Connection)
  173. };
  174. //==============================================================================
  175. ChildProcessSlave::ChildProcessSlave() {}
  176. ChildProcessSlave::~ChildProcessSlave() {}
  177. void ChildProcessSlave::handleConnectionMade() {}
  178. void ChildProcessSlave::handleConnectionLost() {}
  179. bool ChildProcessSlave::sendMessageToMaster (const MemoryBlock& mb)
  180. {
  181. if (connection != nullptr)
  182. return connection->sendMessage (mb);
  183. jassertfalse; // this can only be used when the connection is active!
  184. return false;
  185. }
  186. bool ChildProcessSlave::initialiseFromCommandLine (const String& commandLine,
  187. const String& commandLineUniqueID,
  188. int timeoutMs)
  189. {
  190. auto prefix = getCommandLinePrefix (commandLineUniqueID);
  191. if (commandLine.trim().startsWith (prefix))
  192. {
  193. auto pipeName = commandLine.fromFirstOccurrenceOf (prefix, false, false)
  194. .upToFirstOccurrenceOf (" ", false, false).trim();
  195. if (pipeName.isNotEmpty())
  196. {
  197. connection.reset (new Connection (*this, pipeName, timeoutMs <= 0 ? defaultTimeoutMs : timeoutMs));
  198. if (! connection->isConnected())
  199. connection.reset();
  200. }
  201. }
  202. return connection != nullptr;
  203. }
  204. } // namespace juce