llprocesslauncher.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /**
  2. * @file llprocesslauncher.cpp
  3. * @brief Utility class for launching, terminating, and tracking the state of
  4. * processes.
  5. *
  6. * $LicenseInfo:firstyear=2008&license=viewergpl$
  7. *
  8. * Copyright (c) 2008-2009, Linden Research, Inc.
  9. *
  10. * Second Life Viewer Source Code
  11. * The source code in this file ("Source Code") is provided by Linden Lab
  12. * to you under the terms of the GNU General Public License, version 2.0
  13. * ("GPL"), unless you have obtained a separate licensing agreement
  14. * ("Other License"), formally executed by you and Linden Lab. Terms of
  15. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  16. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  17. *
  18. * There are special exceptions to the terms and conditions of the GPL as
  19. * it is applied to this Source Code. View the full text of the exception
  20. * in the file doc/FLOSS-exception.txt in this software distribution, or
  21. * online at
  22. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  23. *
  24. * By copying, modifying or distributing this software, you acknowledge
  25. * that you have read and understood your obligations described above,
  26. * and agree to abide by those obligations.
  27. *
  28. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  29. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  30. * COMPLETENESS OR PERFORMANCE.
  31. * $/LicenseInfo$
  32. */
  33. #include "linden_common.h"
  34. #include "llprocesslauncher.h"
  35. #if LL_DARWIN || LL_LINUX
  36. # include <sys/wait.h>
  37. # include <unistd.h>
  38. # include <signal.h>
  39. # include <fcntl.h>
  40. # include <errno.h>
  41. #endif
  42. // Sadly, some gcc/glibc "flavours" (Ubuntu's ones, apparently), warn about
  43. // unused results for (void)chdir() and (void)fchdir(), even though the (void)
  44. // is there to prevent this ! So, let's take more radical measures...
  45. #if LL_LINUX && defined(__GNUC__)
  46. # pragma GCC diagnostic ignored "-Wunused-result"
  47. #endif
  48. LLProcessLauncher::LLProcessLauncher()
  49. {
  50. #if LL_WINDOWS
  51. mProcessHandle = 0;
  52. #else
  53. mProcessID = 0;
  54. #endif
  55. }
  56. LLProcessLauncher::~LLProcessLauncher()
  57. {
  58. kill();
  59. }
  60. #if LL_WINDOWS
  61. S32 LLProcessLauncher::launch()
  62. {
  63. // If there was already a process associated with this object, kill it.
  64. kill();
  65. orphan();
  66. S32 result = 0;
  67. PROCESS_INFORMATION pinfo;
  68. STARTUPINFOA sinfo;
  69. memset(&sinfo, 0, sizeof(sinfo));
  70. std::string args = "\"" + mExecutable + "\"";
  71. for (S32 i = 0, count = mLaunchArguments.size(); i < count; ++i)
  72. {
  73. args += ' ';
  74. const std::string& arg = mLaunchArguments[i];
  75. if (arg.find(' ') != std::string::npos)
  76. {
  77. // Quote arguments containing spaces !
  78. args += "\"" + arg + "\"";
  79. }
  80. else
  81. {
  82. args += arg;
  83. }
  84. }
  85. llinfos << "Executable: " << mExecutable << " arguments: " << args
  86. << llendl;
  87. // So retarded. Windows requires that the second parameter to
  88. // CreateProcessA be a writable (non-const) string...
  89. char* args2 = new char[args.size() + 1];
  90. strcpy(args2, args.c_str());
  91. if (!CreateProcessA(NULL, args2, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo,
  92. &pinfo))
  93. {
  94. // *TODO: do better than returning the OS-specific error code on
  95. // failure...
  96. result = GetLastError();
  97. if (result == 0)
  98. {
  99. // Make absolutely certain we return a non-zero value on failure.
  100. result = -1;
  101. }
  102. }
  103. else
  104. {
  105. // foo = pinfo.dwProcessId; // Get your pid here if you want to use it
  106. // later on
  107. mProcessHandle = pinfo.hProcess;
  108. CloseHandle(pinfo.hThread); // Stops leaks, nothing else
  109. }
  110. delete[] args2;
  111. return result;
  112. }
  113. bool LLProcessLauncher::isRunning()
  114. {
  115. if (mProcessHandle)
  116. {
  117. if (WaitForSingleObject(mProcessHandle, 0) == WAIT_OBJECT_0)
  118. {
  119. // The process has completed.
  120. mProcessHandle = 0;
  121. }
  122. }
  123. return mProcessHandle != 0;
  124. }
  125. bool LLProcessLauncher::kill()
  126. {
  127. if (mProcessHandle)
  128. {
  129. TerminateProcess(mProcessHandle, 0);
  130. if (isRunning())
  131. {
  132. return false;
  133. }
  134. }
  135. return true;
  136. }
  137. void LLProcessLauncher::orphan()
  138. {
  139. // Forget about the process
  140. mProcessHandle = 0;
  141. }
  142. //static
  143. void LLProcessLauncher::reap()
  144. {
  145. // No actions necessary on Windows.
  146. }
  147. #else // Linux and macOS
  148. static std::list<pid_t> sZombies;
  149. // Attempts to reap a process Id. Returns true if the process has exited and has
  150. // been reaped, false otherwise.
  151. static bool reap_pid(pid_t pid)
  152. {
  153. bool result = false;
  154. pid_t wait_result = ::waitpid(pid, NULL, WNOHANG);
  155. if (wait_result == pid)
  156. {
  157. result = true;
  158. }
  159. else if (wait_result == -1)
  160. {
  161. if (errno == ECHILD)
  162. {
  163. // No such process: this may mean we are ignoring SIGCHILD.
  164. result = true;
  165. }
  166. }
  167. return result;
  168. }
  169. S32 LLProcessLauncher::launch()
  170. {
  171. // If there was already a process associated with this object, kill it.
  172. kill();
  173. orphan();
  174. // Create an argv vector for the child process (size + 1 for the executable
  175. // path and + 1 for the NULL terminator)
  176. const char** fake_argv = new const char *[mLaunchArguments.size() + 2];
  177. S32 i = 0;
  178. // Add the executable path
  179. fake_argv[i++] = mExecutable.c_str();
  180. // And any arguments
  181. for (U32 j = 0, count = mLaunchArguments.size(); j < count; ++j)
  182. {
  183. fake_argv[i++] = mLaunchArguments[j].c_str();
  184. }
  185. // Terminate with a null pointer
  186. fake_argv[i] = NULL;
  187. int current_wd = -1;
  188. if (!mWorkingDir.empty())
  189. {
  190. // Save the current working directory
  191. current_wd = open(".", O_RDONLY);
  192. // And change to the one the child will be executed in
  193. (void)chdir(mWorkingDir.c_str());
  194. }
  195. // Flush all buffers before the child inherits them
  196. fflush(NULL);
  197. pid_t id = fork();
  198. if (id == 0)
  199. {
  200. // Child process code path
  201. execv(mExecutable.c_str(), (char* const*)fake_argv);
  202. // If we reach this point, the exec failed. Use _exit() instead of
  203. // exit() per the fork man page.
  204. _exit(0);
  205. }
  206. // Parent process code path
  207. if (current_wd >= 0)
  208. {
  209. // Restore the previous working directory
  210. (void)fchdir(current_wd);
  211. (void)close(current_wd);
  212. }
  213. delete[] fake_argv;
  214. mProcessID = id;
  215. // At this point, the child process will have been created (since that is
  216. // how fork works: the child borrowed our execution context until it
  217. // forked). If the process does not exist at this point, the exec failed.
  218. if (!isRunning())
  219. {
  220. llwarns << "Failed to exec: " << mExecutable << llendl;
  221. return -1;
  222. }
  223. LL_DEBUGS("ProcessLauncher") << "Successfully launched: " << mExecutable
  224. << " - pid = " << mProcessID << LL_ENDL;
  225. return 0;
  226. }
  227. bool LLProcessLauncher::isRunning()
  228. {
  229. if (mProcessID)
  230. {
  231. LL_DEBUGS("ProcessLauncher") << "Testing status of: " << mExecutable
  232. << " - pid = " << mProcessID << LL_ENDL;
  233. // Check whether the process has exited, and reap it if it has.
  234. if (reap_pid(mProcessID))
  235. {
  236. // The process has exited.
  237. mProcessID = 0;
  238. }
  239. }
  240. LL_DEBUGS("ProcessLauncher") << "Process for " << mExecutable << " is "
  241. << (mProcessID ? "running" : "terminated")
  242. << LL_ENDL;
  243. return mProcessID != 0;
  244. }
  245. bool LLProcessLauncher::kill()
  246. {
  247. if (mProcessID)
  248. {
  249. // Try to kill the process. We will do approximately the same thing
  250. // whether the kill returns an error or not, so we ignore the result.
  251. (void)::kill(mProcessID, SIGTERM);
  252. // This will have the side-effect of reaping the zombie if the process
  253. // has exited.
  254. if (isRunning())
  255. {
  256. return false;
  257. }
  258. }
  259. return true;
  260. }
  261. void LLProcessLauncher::orphan()
  262. {
  263. // Disassociate the process from this object
  264. if (mProcessID)
  265. {
  266. // We may still need to reap the process's zombie eventually
  267. sZombies.push_back(mProcessID);
  268. mProcessID = 0;
  269. }
  270. }
  271. //static
  272. void LLProcessLauncher::reap()
  273. {
  274. // Attempt to reap all saved process ID's.
  275. std::list<pid_t>::iterator iter = sZombies.begin();
  276. while (iter != sZombies.end())
  277. {
  278. if (reap_pid(*iter))
  279. {
  280. iter = sZombies.erase(iter);
  281. }
  282. else
  283. {
  284. ++iter;
  285. }
  286. }
  287. }
  288. #endif // Linux and macOS