/std/process.d

http://github.com/jcd/phobos · D · 3445 lines · 2014 code · 302 blank · 1129 comment · 392 complexity · c9ae7d4412c9f60edf2d104d11570b7e MD5 · raw file

Large files are truncated click here to view the full file

  1. // Written in the D programming language.
  2. /**
  3. Functions for starting and interacting with other processes, and for
  4. working with the current _process' execution environment.
  5. Process_handling:
  6. $(UL $(LI
  7. $(LREF spawnProcess) spawns a new _process, optionally assigning it an
  8. arbitrary set of standard input, output, and error streams.
  9. The function returns immediately, leaving the child _process to execute
  10. in parallel with its parent. All other functions in this module that
  11. spawn processes are built around $(D spawnProcess).)
  12. $(LI
  13. $(LREF wait) makes the parent _process wait for a child _process to
  14. terminate. In general one should always do this, to avoid
  15. child processes becoming "zombies" when the parent _process exits.
  16. Scope guards are perfect for this – see the $(LREF spawnProcess)
  17. documentation for examples. $(LREF tryWait) is similar to $(D wait),
  18. but does not block if the _process has not yet terminated.)
  19. $(LI
  20. $(LREF pipeProcess) also spawns a child _process which runs
  21. in parallel with its parent. However, instead of taking
  22. arbitrary streams, it automatically creates a set of
  23. pipes that allow the parent to communicate with the child
  24. through the child's standard input, output, and/or error streams.
  25. This function corresponds roughly to C's $(D popen) function.)
  26. $(LI
  27. $(LREF execute) starts a new _process and waits for it
  28. to complete before returning. Additionally, it captures
  29. the _process' standard output and error streams and returns
  30. the output of these as a string.)
  31. $(LI
  32. $(LREF spawnShell), $(LREF pipeShell) and $(LREF executeShell) work like
  33. $(D spawnProcess), $(D pipeProcess) and $(D execute), respectively,
  34. except that they take a single command string and run it through
  35. the current user's default command interpreter.
  36. $(D executeShell) corresponds roughly to C's $(D system) function.)
  37. $(LI
  38. $(LREF kill) attempts to terminate a running _process.)
  39. )
  40. The following table compactly summarises the different _process creation
  41. functions and how they relate to each other:
  42. $(BOOKTABLE,
  43. $(TR $(TH )
  44. $(TH Runs program directly)
  45. $(TH Runs shell command))
  46. $(TR $(TD Low-level _process creation)
  47. $(TD $(LREF spawnProcess))
  48. $(TD $(LREF spawnShell)))
  49. $(TR $(TD Automatic input/output redirection using pipes)
  50. $(TD $(LREF pipeProcess))
  51. $(TD $(LREF pipeShell)))
  52. $(TR $(TD Execute and wait for completion, collect output)
  53. $(TD $(LREF execute))
  54. $(TD $(LREF executeShell)))
  55. )
  56. Other_functionality:
  57. $(UL
  58. $(LI
  59. $(LREF pipe) is used to create unidirectional pipes.)
  60. $(LI
  61. $(LREF environment) is an interface through which the current _process'
  62. environment variables can be read and manipulated.)
  63. $(LI
  64. $(LREF escapeShellCommand) and $(LREF escapeShellFileName) are useful
  65. for constructing shell command lines in a portable way.)
  66. )
  67. Authors:
  68. $(LINK2 https://github.com/kyllingstad, Lars Tandle Kyllingstad),
  69. $(LINK2 https://github.com/schveiguy, Steven Schveighoffer),
  70. $(WEB thecybershadow.net, Vladimir Panteleev)
  71. Copyright:
  72. Copyright (c) 2013, the authors. All rights reserved.
  73. Source:
  74. $(PHOBOSSRC std/_process.d)
  75. Macros:
  76. WIKI=Phobos/StdProcess
  77. OBJECTREF=$(D $(LINK2 object.html#$0,$0))
  78. LREF=$(D $(LINK2 #.$0,$0))
  79. */
  80. module std.process;
  81. version (Posix)
  82. {
  83. import core.stdc.errno;
  84. import core.stdc.string;
  85. import core.sys.posix.stdio;
  86. import core.sys.posix.unistd;
  87. import core.sys.posix.sys.wait;
  88. }
  89. version (Windows)
  90. {
  91. import core.stdc.stdio;
  92. import core.sys.windows.windows;
  93. import std.utf;
  94. import std.windows.syserror;
  95. }
  96. import std.algorithm;
  97. import std.array;
  98. import std.conv;
  99. import std.exception;
  100. import std.path;
  101. import std.stdio;
  102. import std.string;
  103. import std.internal.processinit;
  104. // When the DMC runtime is used, we have to use some custom functions
  105. // to convert between Windows file handles and FILE*s.
  106. version (Win32) version (DigitalMars) version = DMC_RUNTIME;
  107. // Some of the following should be moved to druntime.
  108. private
  109. {
  110. // Microsoft Visual C Runtime (MSVCRT) declarations.
  111. version (Windows)
  112. {
  113. version (DMC_RUNTIME) { } else
  114. {
  115. import core.stdc.stdint;
  116. extern(C)
  117. {
  118. int _fileno(FILE* stream);
  119. HANDLE _get_osfhandle(int fd);
  120. int _open_osfhandle(HANDLE osfhandle, int flags);
  121. FILE* _fdopen(int fd, const (char)* mode);
  122. int _close(int fd);
  123. }
  124. enum
  125. {
  126. STDIN_FILENO = 0,
  127. STDOUT_FILENO = 1,
  128. STDERR_FILENO = 2,
  129. }
  130. enum
  131. {
  132. _O_RDONLY = 0x0000,
  133. _O_APPEND = 0x0004,
  134. _O_TEXT = 0x4000,
  135. }
  136. }
  137. }
  138. // POSIX API declarations.
  139. version (Posix)
  140. {
  141. version (OSX)
  142. {
  143. extern(C) char*** _NSGetEnviron() nothrow;
  144. private __gshared const(char**)* environPtr;
  145. extern(C) void std_process_shared_static_this() { environPtr = _NSGetEnviron(); }
  146. const(char**) environ() @property @trusted nothrow { return *environPtr; }
  147. }
  148. else
  149. {
  150. // Made available by the C runtime:
  151. extern(C) extern __gshared const char** environ;
  152. }
  153. unittest
  154. {
  155. new Thread({assert(environ !is null);}).start();
  156. }
  157. }
  158. } // private
  159. // =============================================================================
  160. // Functions and classes for process management.
  161. // =============================================================================
  162. /**
  163. Spawns a new _process, optionally assigning it an arbitrary set of standard
  164. input, output, and error streams.
  165. The function returns immediately, leaving the child _process to execute
  166. in parallel with its parent. It is recommended to always call $(LREF wait)
  167. on the returned $(LREF Pid), as detailed in the documentation for $(D wait).
  168. Command_line:
  169. There are four overloads of this function. The first two take an array
  170. of strings, $(D args), which should contain the program name as the
  171. zeroth element and any command-line arguments in subsequent elements.
  172. The third and fourth versions are included for convenience, and may be
  173. used when there are no command-line arguments. They take a single string,
  174. $(D program), which specifies the program name.
  175. Unless a directory is specified in $(D args[0]) or $(D program),
  176. $(D spawnProcess) will search for the program in a platform-dependent
  177. manner. On POSIX systems, it will look for the executable in the
  178. directories listed in the PATH environment variable, in the order
  179. they are listed. On Windows, it will search for the executable in
  180. the following sequence:
  181. $(OL
  182. $(LI The directory from which the application loaded.)
  183. $(LI The current directory for the parent process.)
  184. $(LI The 32-bit Windows system directory.)
  185. $(LI The 16-bit Windows system directory.)
  186. $(LI The Windows directory.)
  187. $(LI The directories listed in the PATH environment variable.)
  188. )
  189. ---
  190. // Run an executable called "prog" located in the current working
  191. // directory:
  192. auto pid = spawnProcess("./prog");
  193. scope(exit) wait(pid);
  194. // We can do something else while the program runs. The scope guard
  195. // ensures that the process is waited for at the end of the scope.
  196. ...
  197. // Run DMD on the file "myprog.d", specifying a few compiler switches:
  198. auto dmdPid = spawnProcess(["dmd", "-O", "-release", "-inline", "myprog.d" ]);
  199. if (wait(dmdPid) != 0)
  200. writeln("Compilation failed!");
  201. ---
  202. Environment_variables:
  203. By default, the child process inherits the environment of the parent
  204. process, along with any additional variables specified in the $(D env)
  205. parameter. If the same variable exists in both the parent's environment
  206. and in $(D env), the latter takes precedence.
  207. If the $(LREF Config.newEnv) flag is set in $(D config), the child
  208. process will $(I not) inherit the parent's environment. Its entire
  209. environment will then be determined by $(D env).
  210. ---
  211. wait(spawnProcess("myapp", ["foo" : "bar"], Config.newEnv));
  212. ---
  213. Standard_streams:
  214. The optional arguments $(D stdin), $(D stdout) and $(D stderr) may
  215. be used to assign arbitrary $(XREF stdio,File) objects as the standard
  216. input, output and error streams, respectively, of the child process. The
  217. former must be opened for reading, while the latter two must be opened for
  218. writing. The default is for the child process to inherit the standard
  219. streams of its parent.
  220. ---
  221. // Run DMD on the file myprog.d, logging any error messages to a
  222. // file named errors.log.
  223. auto logFile = File("errors.log", "w");
  224. auto pid = spawnProcess(["dmd", "myprog.d"],
  225. std.stdio.stdin,
  226. std.stdio.stdout,
  227. logFile);
  228. if (wait(pid) != 0)
  229. writeln("Compilation failed. See errors.log for details.");
  230. ---
  231. Note that if you pass a $(D File) object that is $(I not)
  232. one of the standard input/output/error streams of the parent process,
  233. that stream will by default be $(I closed) in the parent process when
  234. this function returns. See the $(LREF Config) documentation below for
  235. information about how to disable this behaviour.
  236. Beware of buffering issues when passing $(D File) objects to
  237. $(D spawnProcess). The child process will inherit the low-level raw
  238. read/write offset associated with the underlying file descriptor, but
  239. it will not be aware of any buffered data. In cases where this matters
  240. (e.g. when a file should be aligned before being passed on to the
  241. child process), it may be a good idea to use unbuffered streams, or at
  242. least ensure all relevant buffers are flushed.
  243. Params:
  244. args = An array which contains the program name as the zeroth element
  245. and any command-line arguments in the following elements.
  246. stdin = The standard input stream of the child process.
  247. This can be any $(XREF stdio,File) that is opened for reading.
  248. By default the child process inherits the parent's input
  249. stream.
  250. stdout = The standard output stream of the child process.
  251. This can be any $(XREF stdio,File) that is opened for writing.
  252. By default the child process inherits the parent's output stream.
  253. stderr = The standard error stream of the child process.
  254. This can be any $(XREF stdio,File) that is opened for writing.
  255. By default the child process inherits the parent's error stream.
  256. env = Additional environment variables for the child process.
  257. config = Flags that control process creation. See $(LREF Config)
  258. for an overview of available flags.
  259. Returns:
  260. A $(LREF Pid) object that corresponds to the spawned process.
  261. Throws:
  262. $(LREF ProcessException) on failure to start the process.$(BR)
  263. $(XREF stdio,StdioException) on failure to pass one of the streams
  264. to the child process (Windows only).$(BR)
  265. $(CXREF exception,RangeError) if $(D args) is empty.
  266. */
  267. Pid spawnProcess(in char[][] args,
  268. File stdin = std.stdio.stdin,
  269. File stdout = std.stdio.stdout,
  270. File stderr = std.stdio.stderr,
  271. const string[string] env = null,
  272. Config config = Config.none)
  273. @trusted // TODO: Should be @safe
  274. {
  275. version (Windows) auto args2 = escapeShellArguments(args);
  276. else version (Posix) alias args2 = args;
  277. return spawnProcessImpl(args2, stdin, stdout, stderr, env, config);
  278. }
  279. /// ditto
  280. Pid spawnProcess(in char[][] args,
  281. const string[string] env,
  282. Config config = Config.none)
  283. @trusted // TODO: Should be @safe
  284. {
  285. return spawnProcess(args,
  286. std.stdio.stdin,
  287. std.stdio.stdout,
  288. std.stdio.stderr,
  289. env,
  290. config);
  291. }
  292. /// ditto
  293. Pid spawnProcess(in char[] program,
  294. File stdin = std.stdio.stdin,
  295. File stdout = std.stdio.stdout,
  296. File stderr = std.stdio.stderr,
  297. const string[string] env = null,
  298. Config config = Config.none)
  299. @trusted
  300. {
  301. return spawnProcess((&program)[0 .. 1],
  302. stdin, stdout, stderr, env, config);
  303. }
  304. /// ditto
  305. Pid spawnProcess(in char[] program,
  306. const string[string] env,
  307. Config config = Config.none)
  308. @trusted
  309. {
  310. return spawnProcess((&program)[0 .. 1], env, config);
  311. }
  312. /*
  313. Implementation of spawnProcess() for POSIX.
  314. envz should be a zero-terminated array of zero-terminated strings
  315. on the form "var=value".
  316. */
  317. version (Posix)
  318. private Pid spawnProcessImpl(in char[][] args,
  319. File stdin,
  320. File stdout,
  321. File stderr,
  322. const string[string] env,
  323. Config config)
  324. @trusted // TODO: Should be @safe
  325. {
  326. import core.exception: RangeError;
  327. if (args.empty) throw new RangeError();
  328. const(char)[] name = args[0];
  329. if (any!isDirSeparator(name))
  330. {
  331. if (!isExecutable(name))
  332. throw new ProcessException(text("Not an executable file: ", name));
  333. }
  334. else
  335. {
  336. name = searchPathFor(name);
  337. if (name is null)
  338. throw new ProcessException(text("Executable file not found: ", name));
  339. }
  340. // Convert program name and arguments to C-style strings.
  341. auto argz = new const(char)*[args.length+1];
  342. argz[0] = toStringz(name);
  343. foreach (i; 1 .. args.length) argz[i] = toStringz(args[i]);
  344. argz[$-1] = null;
  345. // Prepare environment.
  346. auto envz = createEnv(env, !(config & Config.newEnv));
  347. // Get the file descriptors of the streams.
  348. // These could potentially be invalid, but that is OK. If so, later calls
  349. // to dup2() and close() will just silently fail without causing any harm.
  350. auto stdinFD = core.stdc.stdio.fileno(stdin.getFP());
  351. auto stdoutFD = core.stdc.stdio.fileno(stdout.getFP());
  352. auto stderrFD = core.stdc.stdio.fileno(stderr.getFP());
  353. auto id = fork();
  354. if (id < 0)
  355. throw ProcessException.newFromErrno("Failed to spawn new process");
  356. if (id == 0)
  357. {
  358. // Child process
  359. // Redirect streams and close the old file descriptors.
  360. // In the case that stderr is redirected to stdout, we need
  361. // to backup the file descriptor since stdout may be redirected
  362. // as well.
  363. if (stderrFD == STDOUT_FILENO) stderrFD = dup(stderrFD);
  364. dup2(stdinFD, STDIN_FILENO);
  365. dup2(stdoutFD, STDOUT_FILENO);
  366. dup2(stderrFD, STDERR_FILENO);
  367. // Ensure that the standard streams aren't closed on execute, and
  368. // optionally close all other file descriptors.
  369. setCLOEXEC(STDIN_FILENO, false);
  370. setCLOEXEC(STDOUT_FILENO, false);
  371. setCLOEXEC(STDERR_FILENO, false);
  372. if (!(config & Config.inheritFDs))
  373. {
  374. import core.sys.posix.sys.resource;
  375. rlimit r;
  376. getrlimit(RLIMIT_NOFILE, &r);
  377. foreach (i; 3 .. cast(int) r.rlim_cur) close(i);
  378. }
  379. // Close the old file descriptors, unless they are
  380. // either of the standard streams.
  381. if (stdinFD > STDERR_FILENO) close(stdinFD);
  382. if (stdoutFD > STDERR_FILENO) close(stdoutFD);
  383. if (stderrFD > STDERR_FILENO) close(stderrFD);
  384. // Execute program.
  385. core.sys.posix.unistd.execve(argz[0], argz.ptr, envz);
  386. // If execution fails, exit as quickly as possible.
  387. core.sys.posix.stdio.perror("spawnProcess(): Failed to execute program");
  388. core.sys.posix.unistd._exit(1);
  389. assert (0);
  390. }
  391. else
  392. {
  393. // Parent process: Close streams and return.
  394. if (stdinFD > STDERR_FILENO && !(config & Config.retainStdin))
  395. stdin.close();
  396. if (stdoutFD > STDERR_FILENO && !(config & Config.retainStdout))
  397. stdout.close();
  398. if (stderrFD > STDERR_FILENO && !(config & Config.retainStderr))
  399. stderr.close();
  400. return new Pid(id);
  401. }
  402. }
  403. /*
  404. Implementation of spawnProcess() for Windows.
  405. commandLine must contain the entire command line, properly
  406. quoted/escaped as required by CreateProcessW().
  407. envz must be a pointer to a block of UTF-16 characters on the form
  408. "var1=value1\0var2=value2\0...varN=valueN\0\0".
  409. */
  410. version (Windows)
  411. private Pid spawnProcessImpl(in char[] commandLine,
  412. File stdin,
  413. File stdout,
  414. File stderr,
  415. const string[string] env,
  416. Config config)
  417. @trusted
  418. {
  419. import core.exception: RangeError;
  420. if (commandLine.empty) throw new RangeError("Command line is empty");
  421. auto commandz = toUTFz!(wchar*)(commandLine);
  422. // Prepare environment.
  423. auto envz = createEnv(env, !(config & Config.newEnv));
  424. // Startup info for CreateProcessW().
  425. STARTUPINFO_W startinfo;
  426. startinfo.cb = startinfo.sizeof;
  427. startinfo.dwFlags = STARTF_USESTDHANDLES;
  428. // Extract file descriptors and HANDLEs from the streams and make the
  429. // handles inheritable.
  430. static void prepareStream(ref File file, DWORD stdHandle, string which,
  431. out int fileDescriptor, out HANDLE handle)
  432. {
  433. fileDescriptor = _fileno(file.getFP());
  434. if (fileDescriptor < 0) handle = GetStdHandle(stdHandle);
  435. else
  436. {
  437. version (DMC_RUNTIME) handle = _fdToHandle(fileDescriptor);
  438. else /* MSVCRT */ handle = _get_osfhandle(fileDescriptor);
  439. }
  440. DWORD dwFlags;
  441. if (GetHandleInformation(handle, &dwFlags))
  442. {
  443. if (!(dwFlags & HANDLE_FLAG_INHERIT))
  444. {
  445. if (!SetHandleInformation(handle,
  446. HANDLE_FLAG_INHERIT,
  447. HANDLE_FLAG_INHERIT))
  448. {
  449. throw new StdioException(
  450. "Failed to make "~which~" stream inheritable by child process ("
  451. ~sysErrorString(GetLastError()) ~ ')',
  452. 0);
  453. }
  454. }
  455. }
  456. }
  457. int stdinFD = -1, stdoutFD = -1, stderrFD = -1;
  458. prepareStream(stdin, STD_INPUT_HANDLE, "stdin" , stdinFD, startinfo.hStdInput );
  459. prepareStream(stdout, STD_OUTPUT_HANDLE, "stdout", stdoutFD, startinfo.hStdOutput);
  460. prepareStream(stderr, STD_ERROR_HANDLE, "stderr", stderrFD, startinfo.hStdError );
  461. // Create process.
  462. PROCESS_INFORMATION pi;
  463. DWORD dwCreationFlags =
  464. CREATE_UNICODE_ENVIRONMENT |
  465. ((config & Config.suppressConsole) ? CREATE_NO_WINDOW : 0);
  466. if (!CreateProcessW(null, commandz, null, null, true, dwCreationFlags,
  467. envz, null, &startinfo, &pi))
  468. throw ProcessException.newFromLastError("Failed to spawn new process");
  469. // figure out if we should close any of the streams
  470. if (stdinFD > STDERR_FILENO && !(config & Config.retainStdin))
  471. stdin.close();
  472. if (stdoutFD > STDERR_FILENO && !(config & Config.retainStdout))
  473. stdout.close();
  474. if (stderrFD > STDERR_FILENO && !(config & Config.retainStderr))
  475. stderr.close();
  476. // close the thread handle in the process info structure
  477. CloseHandle(pi.hThread);
  478. return new Pid(pi.dwProcessId, pi.hProcess);
  479. }
  480. // Converts childEnv to a zero-terminated array of zero-terminated strings
  481. // on the form "name=value", optionally adding those of the current process'
  482. // environment strings that are not present in childEnv. If the parent's
  483. // environment should be inherited without modification, this function
  484. // returns environ directly.
  485. version (Posix)
  486. private const(char*)* createEnv(const string[string] childEnv,
  487. bool mergeWithParentEnv)
  488. {
  489. // Determine the number of strings in the parent's environment.
  490. int parentEnvLength = 0;
  491. if (mergeWithParentEnv)
  492. {
  493. if (childEnv.length == 0) return environ;
  494. while (environ[parentEnvLength] != null) ++parentEnvLength;
  495. }
  496. // Convert the "new" variables to C-style strings.
  497. auto envz = new const(char)*[parentEnvLength + childEnv.length + 1];
  498. int pos = 0;
  499. foreach (var, val; childEnv)
  500. envz[pos++] = (var~'='~val~'\0').ptr;
  501. // Add the parent's environment.
  502. foreach (environStr; environ[0 .. parentEnvLength])
  503. {
  504. int eqPos = 0;
  505. while (environStr[eqPos] != '=' && environStr[eqPos] != '\0') ++eqPos;
  506. if (environStr[eqPos] != '=') continue;
  507. auto var = environStr[0 .. eqPos];
  508. if (var in childEnv) continue;
  509. envz[pos++] = environStr;
  510. }
  511. envz[pos] = null;
  512. return envz.ptr;
  513. }
  514. version (Posix) unittest
  515. {
  516. auto e1 = createEnv(null, false);
  517. assert (e1 != null && *e1 == null);
  518. auto e2 = createEnv(null, true);
  519. assert (e2 != null);
  520. int i = 0;
  521. for (; environ[i] != null; ++i)
  522. {
  523. assert (e2[i] != null);
  524. import core.stdc.string;
  525. assert (strcmp(e2[i], environ[i]) == 0);
  526. }
  527. assert (e2[i] == null);
  528. auto e3 = createEnv(["foo" : "bar", "hello" : "world"], false);
  529. assert (e3 != null && e3[0] != null && e3[1] != null && e3[2] == null);
  530. assert ((e3[0][0 .. 8] == "foo=bar\0" && e3[1][0 .. 12] == "hello=world\0")
  531. || (e3[0][0 .. 12] == "hello=world\0" && e3[1][0 .. 8] == "foo=bar\0"));
  532. }
  533. // Converts childEnv to a Windows environment block, which is on the form
  534. // "name1=value1\0name2=value2\0...nameN=valueN\0\0", optionally adding
  535. // those of the current process' environment strings that are not present
  536. // in childEnv. Returns null if the parent's environment should be
  537. // inherited without modification, as this is what is expected by
  538. // CreateProcess().
  539. version (Windows)
  540. private LPVOID createEnv(const string[string] childEnv,
  541. bool mergeWithParentEnv)
  542. {
  543. if (mergeWithParentEnv && childEnv.length == 0) return null;
  544. auto envz = appender!(wchar[])();
  545. void put(string var, string val)
  546. {
  547. envz.put(var);
  548. envz.put('=');
  549. envz.put(val);
  550. envz.put(cast(wchar) '\0');
  551. }
  552. // Add the variables in childEnv, removing them from parentEnv
  553. // if they exist there too.
  554. auto parentEnv = mergeWithParentEnv ? environment.toAA() : null;
  555. foreach (k, v; childEnv)
  556. {
  557. auto uk = toUpper(k);
  558. put(uk, v);
  559. if (uk in parentEnv) parentEnv.remove(uk);
  560. }
  561. // Add remaining parent environment variables.
  562. foreach (k, v; parentEnv) put(k, v);
  563. // Two final zeros are needed in case there aren't any environment vars,
  564. // and the last one does no harm when there are.
  565. envz.put("\0\0"w);
  566. return envz.data.ptr;
  567. }
  568. version (Windows) unittest
  569. {
  570. assert (createEnv(null, true) == null);
  571. assert ((cast(wchar*) createEnv(null, false))[0 .. 2] == "\0\0"w);
  572. auto e1 = (cast(wchar*) createEnv(["foo":"bar", "ab":"c"], false))[0 .. 14];
  573. assert (e1 == "FOO=bar\0AB=c\0\0"w || e1 == "AB=c\0FOO=bar\0\0"w);
  574. }
  575. // Searches the PATH variable for the given executable file,
  576. // (checking that it is in fact executable).
  577. version (Posix)
  578. private string searchPathFor(in char[] executable)
  579. @trusted //TODO: @safe nothrow
  580. {
  581. auto pathz = core.stdc.stdlib.getenv("PATH");
  582. if (pathz == null) return null;
  583. foreach (dir; splitter(to!string(pathz), ':'))
  584. {
  585. auto execPath = buildPath(dir, executable);
  586. if (isExecutable(execPath)) return execPath;
  587. }
  588. return null;
  589. }
  590. // Checks whether the file exists and can be executed by the
  591. // current user.
  592. version (Posix)
  593. private bool isExecutable(in char[] path) @trusted //TODO: @safe nothrow
  594. {
  595. return (access(toStringz(path), X_OK) == 0);
  596. }
  597. version (Posix) unittest
  598. {
  599. auto unamePath = searchPathFor("uname");
  600. assert (!unamePath.empty);
  601. assert (unamePath[0] == '/');
  602. assert (unamePath.endsWith("uname"));
  603. auto unlikely = searchPathFor("lkmqwpoialhggyaofijadsohufoiqezm");
  604. assert (unlikely is null, "Are you kidding me?");
  605. }
  606. // Sets or unsets the FD_CLOEXEC flag on the given file descriptor.
  607. version (Posix)
  608. private void setCLOEXEC(int fd, bool on)
  609. {
  610. import core.sys.posix.fcntl;
  611. auto flags = fcntl(fd, F_GETFD);
  612. if (flags >= 0)
  613. {
  614. if (on) flags |= FD_CLOEXEC;
  615. else flags &= ~(cast(typeof(flags)) FD_CLOEXEC);
  616. flags = fcntl(fd, F_SETFD, flags);
  617. }
  618. if (flags == -1)
  619. {
  620. throw new StdioException("Failed to "~(on ? "" : "un")
  621. ~"set close-on-exec flag on file descriptor");
  622. }
  623. }
  624. unittest // Command line arguments in spawnProcess().
  625. {
  626. version (Windows) TestScript prog =
  627. "if not [%~1]==[foo] ( exit 1 )
  628. if not [%~2]==[bar] ( exit 2 )
  629. exit 0";
  630. else version (Posix) TestScript prog =
  631. `if test "$1" != "foo"; then exit 1; fi
  632. if test "$2" != "bar"; then exit 2; fi
  633. exit 0`;
  634. assert (wait(spawnProcess(prog.path)) == 1);
  635. assert (wait(spawnProcess([prog.path])) == 1);
  636. assert (wait(spawnProcess([prog.path, "foo"])) == 2);
  637. assert (wait(spawnProcess([prog.path, "foo", "baz"])) == 2);
  638. assert (wait(spawnProcess([prog.path, "foo", "bar"])) == 0);
  639. }
  640. unittest // Environment variables in spawnProcess().
  641. {
  642. // We really should use set /a on Windows, but Wine doesn't support it.
  643. version (Windows) TestScript envProg =
  644. `if [%STD_PROCESS_UNITTEST1%] == [1] (
  645. if [%STD_PROCESS_UNITTEST2%] == [2] (exit 3)
  646. exit 1
  647. )
  648. if [%STD_PROCESS_UNITTEST1%] == [4] (
  649. if [%STD_PROCESS_UNITTEST2%] == [2] (exit 6)
  650. exit 4
  651. )
  652. if [%STD_PROCESS_UNITTEST2%] == [2] (exit 2)
  653. exit 0`;
  654. version (Posix) TestScript envProg =
  655. `if test "$std_process_unittest1" = ""; then
  656. std_process_unittest1=0
  657. fi
  658. if test "$std_process_unittest2" = ""; then
  659. std_process_unittest2=0
  660. fi
  661. exit $(($std_process_unittest1+$std_process_unittest2))`;
  662. environment.remove("std_process_unittest1"); // Just in case.
  663. environment.remove("std_process_unittest2");
  664. assert (wait(spawnProcess(envProg.path)) == 0);
  665. assert (wait(spawnProcess(envProg.path, null, Config.newEnv)) == 0);
  666. environment["std_process_unittest1"] = "1";
  667. assert (wait(spawnProcess(envProg.path)) == 1);
  668. assert (wait(spawnProcess(envProg.path, null, Config.newEnv)) == 0);
  669. auto env = ["std_process_unittest2" : "2"];
  670. assert (wait(spawnProcess(envProg.path, env)) == 3);
  671. assert (wait(spawnProcess(envProg.path, env, Config.newEnv)) == 2);
  672. env["std_process_unittest1"] = "4";
  673. assert (wait(spawnProcess(envProg.path, env)) == 6);
  674. assert (wait(spawnProcess(envProg.path, env, Config.newEnv)) == 6);
  675. environment.remove("std_process_unittest1");
  676. assert (wait(spawnProcess(envProg.path, env)) == 6);
  677. assert (wait(spawnProcess(envProg.path, env, Config.newEnv)) == 6);
  678. }
  679. unittest // Stream redirection in spawnProcess().
  680. {
  681. version (Windows) TestScript prog =
  682. "set /p INPUT=
  683. echo %INPUT% output %~1
  684. echo %INPUT% error %~2 1>&2";
  685. else version (Posix) TestScript prog =
  686. "read INPUT
  687. echo $INPUT output $1
  688. echo $INPUT error $2 >&2";
  689. // Pipes
  690. auto pipei = pipe();
  691. auto pipeo = pipe();
  692. auto pipee = pipe();
  693. auto pid = spawnProcess([prog.path, "foo", "bar"],
  694. pipei.readEnd, pipeo.writeEnd, pipee.writeEnd);
  695. pipei.writeEnd.writeln("input");
  696. pipei.writeEnd.flush();
  697. assert (pipeo.readEnd.readln().chomp() == "input output foo");
  698. assert (pipee.readEnd.readln().chomp().stripRight() == "input error bar");
  699. wait(pid);
  700. // Files
  701. import std.ascii, std.file, std.uuid;
  702. auto pathi = buildPath(tempDir(), randomUUID().toString());
  703. auto patho = buildPath(tempDir(), randomUUID().toString());
  704. auto pathe = buildPath(tempDir(), randomUUID().toString());
  705. std.file.write(pathi, "INPUT"~std.ascii.newline);
  706. auto filei = File(pathi, "r");
  707. auto fileo = File(patho, "w");
  708. auto filee = File(pathe, "w");
  709. pid = spawnProcess([prog.path, "bar", "baz" ], filei, fileo, filee);
  710. wait(pid);
  711. assert (readText(patho).chomp() == "INPUT output bar");
  712. assert (readText(pathe).chomp().stripRight() == "INPUT error baz");
  713. remove(pathi);
  714. remove(patho);
  715. remove(pathe);
  716. }
  717. unittest // Error handling in spawnProcess()
  718. {
  719. assertThrown!ProcessException(spawnProcess("ewrgiuhrifuheiohnmnvqweoijwf"));
  720. assertThrown!ProcessException(spawnProcess("./rgiuhrifuheiohnmnvqweoijwf"));
  721. }
  722. /**
  723. A variation on $(LREF spawnProcess) that runs the given _command through
  724. the current user's preferred _command interpreter (aka. shell).
  725. The string $(D command) is passed verbatim to the shell, and is therefore
  726. subject to its rules about _command structure, argument/filename quoting
  727. and escaping of special characters.
  728. The path to the shell executable is determined by the $(LREF userShell)
  729. function.
  730. In all other respects this function works just like $(D spawnProcess).
  731. Please refer to the $(LREF spawnProcess) documentation for descriptions
  732. of the other function parameters, the return value and any exceptions
  733. that may be thrown.
  734. ---
  735. // Run the command/program "foo" on the file named "my file.txt", and
  736. // redirect its output into foo.log.
  737. auto pid = spawnShell(`foo "my file.txt" > foo.log`);
  738. wait(pid);
  739. ---
  740. See_also:
  741. $(LREF escapeShellCommand), which may be helpful in constructing a
  742. properly quoted and escaped shell _command line for the current platform.
  743. */
  744. Pid spawnShell(in char[] command,
  745. File stdin = std.stdio.stdin,
  746. File stdout = std.stdio.stdout,
  747. File stderr = std.stdio.stderr,
  748. const string[string] env = null,
  749. Config config = Config.none)
  750. @trusted // TODO: Should be @safe
  751. {
  752. version (Windows)
  753. {
  754. auto args = escapeShellArguments(userShell, shellSwitch)
  755. ~ " " ~ command;
  756. }
  757. else version (Posix)
  758. {
  759. const(char)[][3] args;
  760. args[0] = userShell;
  761. args[1] = shellSwitch;
  762. args[2] = command;
  763. }
  764. return spawnProcessImpl(args, stdin, stdout, stderr, env, config);
  765. }
  766. /// ditto
  767. Pid spawnShell(in char[] command,
  768. const string[string] env,
  769. Config config = Config.none)
  770. @trusted // TODO: Should be @safe
  771. {
  772. return spawnShell(command,
  773. std.stdio.stdin,
  774. std.stdio.stdout,
  775. std.stdio.stderr,
  776. env,
  777. config);
  778. }
  779. unittest
  780. {
  781. version (Windows)
  782. auto cmd = "echo %FOO%";
  783. else version (Posix)
  784. auto cmd = "echo $foo";
  785. import std.file;
  786. auto tmpFile = uniqueTempPath();
  787. scope(exit) if (exists(tmpFile)) remove(tmpFile);
  788. auto redir = "> \""~tmpFile~'"';
  789. auto env = ["foo" : "bar"];
  790. assert (wait(spawnShell(cmd~redir, env)) == 0);
  791. auto f = File(tmpFile, "a");
  792. assert (wait(spawnShell(cmd, std.stdio.stdin, f, std.stdio.stderr, env)) == 0);
  793. f.close();
  794. auto output = std.file.readText(tmpFile);
  795. assert (output == "bar\nbar\n" || output == "bar\r\nbar\r\n");
  796. }
  797. /**
  798. Flags that control the behaviour of $(LREF spawnProcess) and
  799. $(LREF spawnShell).
  800. Use bitwise OR to combine flags.
  801. Example:
  802. ---
  803. auto logFile = File("myapp_error.log", "w");
  804. // Start program, suppressing the console window (Windows only),
  805. // redirect its error stream to logFile, and leave logFile open
  806. // in the parent process as well.
  807. auto pid = spawnProcess("myapp", stdin, stdout, logFile,
  808. Config.retainStderr | Config.suppressConsole);
  809. scope(exit)
  810. {
  811. auto exitCode = wait(pid);
  812. logFile.writeln("myapp exited with code ", exitCode);
  813. logFile.close();
  814. }
  815. ---
  816. */
  817. enum Config
  818. {
  819. none = 0,
  820. /**
  821. By default, the child process inherits the parent's environment,
  822. and any environment variables passed to $(LREF spawnProcess) will
  823. be added to it. If this flag is set, the only variables in the
  824. child process' environment will be those given to spawnProcess.
  825. */
  826. newEnv = 1,
  827. /**
  828. Unless the child process inherits the standard input/output/error
  829. streams of its parent, one almost always wants the streams closed
  830. in the parent when $(LREF spawnProcess) returns. Therefore, by
  831. default, this is done. If this is not desirable, pass any of these
  832. options to spawnProcess.
  833. */
  834. retainStdin = 2,
  835. retainStdout = 4, /// ditto
  836. retainStderr = 8, /// ditto
  837. /**
  838. On Windows, if the child process is a console application, this
  839. flag will prevent the creation of a console window. Otherwise,
  840. it will be ignored. On POSIX, $(D suppressConsole) has no effect.
  841. */
  842. suppressConsole = 16,
  843. /**
  844. On POSIX, open $(LINK2 http://en.wikipedia.org/wiki/File_descriptor,file descriptors)
  845. are by default inherited by the child process. As this may lead
  846. to subtle bugs when pipes or multiple threads are involved,
  847. $(LREF spawnProcess) ensures that all file descriptors except the
  848. ones that correspond to standard input/output/error are closed
  849. in the child process when it starts. Use $(D inheritFDs) to prevent
  850. this.
  851. On Windows, this option has no effect, and any handles which have been
  852. explicitly marked as inheritable will always be inherited by the child
  853. process.
  854. */
  855. inheritFDs = 32,
  856. }
  857. /// A handle that corresponds to a spawned process.
  858. final class Pid
  859. {
  860. /**
  861. The process ID number.
  862. This is a number that uniquely identifies the process on the operating
  863. system, for at least as long as the process is running. Once $(LREF wait)
  864. has been called on the $(LREF Pid), this method will return an
  865. invalid process ID.
  866. */
  867. @property int processID() const @safe pure nothrow
  868. {
  869. return _processID;
  870. }
  871. /**
  872. An operating system handle to the process.
  873. This handle is used to specify the process in OS-specific APIs.
  874. On POSIX, this function returns a $(D core.sys.posix.sys.types.pid_t)
  875. with the same value as $(LREF Pid.processID), while on Windows it returns
  876. a $(D core.sys.windows.windows.HANDLE).
  877. Once $(LREF wait) has been called on the $(LREF Pid), this method
  878. will return an invalid handle.
  879. */
  880. // Note: Since HANDLE is a reference, this function cannot be const.
  881. version (Windows)
  882. @property HANDLE osHandle() @safe pure nothrow
  883. {
  884. return _handle;
  885. }
  886. else version (Posix)
  887. @property pid_t osHandle() @safe pure nothrow
  888. {
  889. return _processID;
  890. }
  891. private:
  892. /*
  893. Pid.performWait() does the dirty work for wait() and nonBlockingWait().
  894. If block == true, this function blocks until the process terminates,
  895. sets _processID to terminated, and returns the exit code or terminating
  896. signal as described in the wait() documentation.
  897. If block == false, this function returns immediately, regardless
  898. of the status of the process. If the process has terminated, the
  899. function has the exact same effect as the blocking version. If not,
  900. it returns 0 and does not modify _processID.
  901. */
  902. version (Posix)
  903. int performWait(bool block) @trusted
  904. {
  905. if (_processID == terminated) return _exitCode;
  906. int exitCode;
  907. while(true)
  908. {
  909. int status;
  910. auto check = waitpid(_processID, &status, block ? 0 : WNOHANG);
  911. if (check == -1)
  912. {
  913. if (errno == ECHILD)
  914. {
  915. throw new ProcessException(
  916. "Process does not exist or is not a child process.");
  917. }
  918. else
  919. {
  920. // waitpid() was interrupted by a signal. We simply
  921. // restart it.
  922. assert (errno == EINTR);
  923. continue;
  924. }
  925. }
  926. if (!block && check == 0) return 0;
  927. if (WIFEXITED(status))
  928. {
  929. exitCode = WEXITSTATUS(status);
  930. break;
  931. }
  932. else if (WIFSIGNALED(status))
  933. {
  934. exitCode = -WTERMSIG(status);
  935. break;
  936. }
  937. // We check again whether the call should be blocking,
  938. // since we don't care about other status changes besides
  939. // "exited" and "terminated by signal".
  940. if (!block) return 0;
  941. // Process has stopped, but not terminated, so we continue waiting.
  942. }
  943. // Mark Pid as terminated, and cache and return exit code.
  944. _processID = terminated;
  945. _exitCode = exitCode;
  946. return exitCode;
  947. }
  948. else version (Windows)
  949. {
  950. int performWait(bool block) @trusted
  951. {
  952. if (_processID == terminated) return _exitCode;
  953. assert (_handle != INVALID_HANDLE_VALUE);
  954. if (block)
  955. {
  956. auto result = WaitForSingleObject(_handle, INFINITE);
  957. if (result != WAIT_OBJECT_0)
  958. throw ProcessException.newFromLastError("Wait failed.");
  959. }
  960. if (!GetExitCodeProcess(_handle, cast(LPDWORD)&_exitCode))
  961. throw ProcessException.newFromLastError();
  962. if (!block && _exitCode == STILL_ACTIVE) return 0;
  963. CloseHandle(_handle);
  964. _handle = INVALID_HANDLE_VALUE;
  965. _processID = terminated;
  966. return _exitCode;
  967. }
  968. ~this()
  969. {
  970. if(_handle != INVALID_HANDLE_VALUE)
  971. {
  972. CloseHandle(_handle);
  973. _handle = INVALID_HANDLE_VALUE;
  974. }
  975. }
  976. }
  977. // Special values for _processID.
  978. enum invalid = -1, terminated = -2;
  979. // OS process ID number. Only nonnegative IDs correspond to
  980. // running processes.
  981. int _processID = invalid;
  982. // Exit code cached by wait(). This is only expected to hold a
  983. // sensible value if _processID == terminated.
  984. int _exitCode;
  985. // Pids are only meant to be constructed inside this module, so
  986. // we make the constructor private.
  987. version (Windows)
  988. {
  989. HANDLE _handle = INVALID_HANDLE_VALUE;
  990. this(int pid, HANDLE handle) @safe pure nothrow
  991. {
  992. _processID = pid;
  993. _handle = handle;
  994. }
  995. }
  996. else
  997. {
  998. this(int id) @safe pure nothrow
  999. {
  1000. _processID = id;
  1001. }
  1002. }
  1003. }
  1004. /**
  1005. Waits for the process associated with $(D pid) to terminate, and returns
  1006. its exit status.
  1007. In general one should always _wait for child processes to terminate
  1008. before exiting the parent process. Otherwise, they may become
  1009. "$(WEB en.wikipedia.org/wiki/Zombie_process,zombies)" – processes
  1010. that are defunct, yet still occupy a slot in the OS process table.
  1011. If the process has already terminated, this function returns directly.
  1012. The exit code is cached, so that if wait() is called multiple times on
  1013. the same $(LREF Pid) it will always return the same value.
  1014. POSIX_specific:
  1015. If the process is terminated by a signal, this function returns a
  1016. negative number whose absolute value is the signal number.
  1017. Since POSIX restricts normal exit codes to the range 0-255, a
  1018. negative return value will always indicate termination by signal.
  1019. Signal codes are defined in the $(D core.sys.posix.signal) module
  1020. (which corresponds to the $(D signal.h) POSIX header).
  1021. Throws:
  1022. $(LREF ProcessException) on failure.
  1023. Examples:
  1024. See the $(LREF spawnProcess) documentation.
  1025. See_also:
  1026. $(LREF tryWait), for a non-blocking function.
  1027. */
  1028. int wait(Pid pid) @safe
  1029. {
  1030. assert(pid !is null, "Called wait on a null Pid.");
  1031. return pid.performWait(true);
  1032. }
  1033. unittest // Pid and wait()
  1034. {
  1035. version (Windows) TestScript prog = "exit %~1";
  1036. else version (Posix) TestScript prog = "exit $1";
  1037. assert (wait(spawnProcess([prog.path, "0"])) == 0);
  1038. assert (wait(spawnProcess([prog.path, "123"])) == 123);
  1039. auto pid = spawnProcess([prog.path, "10"]);
  1040. assert (pid.processID > 0);
  1041. version (Windows) assert (pid.osHandle != INVALID_HANDLE_VALUE);
  1042. else version (Posix) assert (pid.osHandle == pid.processID);
  1043. assert (wait(pid) == 10);
  1044. assert (wait(pid) == 10); // cached exit code
  1045. assert (pid.processID < 0);
  1046. version (Windows) assert (pid.osHandle == INVALID_HANDLE_VALUE);
  1047. else version (Posix) assert (pid.osHandle < 0);
  1048. }
  1049. /**
  1050. A non-blocking version of $(LREF wait).
  1051. If the process associated with $(D pid) has already terminated,
  1052. $(D tryWait) has the exact same effect as $(D wait).
  1053. In this case, it returns a struct where the $(D terminated) field
  1054. is set to $(D true) and the $(D status) field has the same
  1055. interpretation as the return value of $(D wait).
  1056. If the process has $(I not) yet terminated, this function differs
  1057. from $(D wait) in that does not wait for this to happen, but instead
  1058. returns immediately. The $(D terminated) field of the returned
  1059. tuple will then be set to $(D false), while the $(D status) field
  1060. will always be 0 (zero). $(D wait) or $(D tryWait) should then be
  1061. called again on the same $(D Pid) at some later time; not only to
  1062. get the exit code, but also to avoid the process becoming a "zombie"
  1063. when it finally terminates. (See $(LREF wait) for details).
  1064. Returns:
  1065. A $(D struct) which contains the fields $(D bool terminated)
  1066. and $(D int status). (This will most likely change to become a
  1067. $(D std.typecons.Tuple!(bool,"terminated",int,"status")) in the future,
  1068. but a compiler bug currently prevents this.)
  1069. Throws:
  1070. $(LREF ProcessException) on failure.
  1071. Example:
  1072. ---
  1073. auto pid = spawnProcess("dmd myapp.d");
  1074. scope(exit) wait(pid);
  1075. ...
  1076. auto dmd = tryWait(pid);
  1077. if (dmd.terminated)
  1078. {
  1079. if (dmd.status == 0) writeln("Compilation succeeded!");
  1080. else writeln("Compilation failed");
  1081. }
  1082. else writeln("Still compiling...");
  1083. ...
  1084. ---
  1085. Note that in this example, the first $(D wait) call will have no
  1086. effect if the process has already terminated by the time $(D tryWait)
  1087. is called. In the opposite case, however, the $(D scope) statement
  1088. ensures that we always wait for the process if it hasn't terminated
  1089. by the time we reach the end of the scope.
  1090. */
  1091. auto tryWait(Pid pid) @safe
  1092. {
  1093. struct TryWaitResult
  1094. {
  1095. bool terminated;
  1096. int status;
  1097. }
  1098. assert(pid !is null, "Called tryWait on a null Pid.");
  1099. auto code = pid.performWait(false);
  1100. return TryWaitResult(pid._processID == Pid.terminated, code);
  1101. }
  1102. // unittest: This function is tested together with kill() below.
  1103. /**
  1104. Attempts to terminate the process associated with $(D pid).
  1105. The effect of this function, as well as the meaning of $(D codeOrSignal),
  1106. is highly platform dependent. Details are given below. Common to all
  1107. platforms is that this function only $(I initiates) termination of the process,
  1108. and returns immediately. It does not wait for the process to end,
  1109. nor does it guarantee that the process does in fact get terminated.
  1110. Always call $(LREF wait) to wait for a process to complete, even if $(D kill)
  1111. has been called on it.
  1112. Windows_specific:
  1113. The process will be
  1114. $(LINK2 http://msdn.microsoft.com/en-us/library/windows/desktop/ms686714%28v=vs.100%29.aspx,
  1115. forcefully and abruptly terminated). If $(D codeOrSignal) is specified, it
  1116. must be a nonnegative number which will be used as the exit code of the process.
  1117. If not, the process wil exit with code 1. Do not use $(D codeOrSignal = 259),
  1118. as this is a special value (aka. $(LINK2 http://msdn.microsoft.com/en-us/library/windows/desktop/ms683189.aspx,STILL_ACTIVE))
  1119. used by Windows to signal that a process has in fact $(I not) terminated yet.
  1120. ---
  1121. auto pid = spawnProcess("some_app");
  1122. kill(pid, 10);
  1123. assert (wait(pid) == 10);
  1124. ---
  1125. POSIX_specific:
  1126. A $(LINK2 http://en.wikipedia.org/wiki/Unix_signal,signal) will be sent to
  1127. the process, whose value is given by $(D codeOrSignal). Depending on the
  1128. signal sent, this may or may not terminate the process. Symbolic constants
  1129. for various $(LINK2 http://en.wikipedia.org/wiki/Unix_signal#POSIX_signals,
  1130. POSIX signals) are defined in $(D core.sys.posix.signal), which corresponds to the
  1131. $(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html,
  1132. $(D signal.h) POSIX header). If $(D codeOrSignal) is omitted, the
  1133. $(D SIGTERM) signal will be sent. (This matches the behaviour of the
  1134. $(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/kill.html,
  1135. $(D _kill)) shell command.)
  1136. ---
  1137. import core.sys.posix.signal: SIGKILL;
  1138. auto pid = spawnProcess("some_app");
  1139. kill(pid, SIGKILL);
  1140. assert (wait(pid) == -SIGKILL); // Negative return value on POSIX!
  1141. ---
  1142. Throws:
  1143. $(LREF ProcessException) on error (e.g. if codeOrSignal is invalid).
  1144. Note that failure to terminate the process is considered a "normal"
  1145. outcome, not an error.$(BR)
  1146. */
  1147. void kill(Pid pid)
  1148. {
  1149. version (Windows) kill(pid, 1);
  1150. else version (Posix)
  1151. {
  1152. import core.sys.posix.signal: SIGTERM;
  1153. kill(pid, SIGTERM);
  1154. }
  1155. }
  1156. /// ditto
  1157. void kill(Pid pid, int codeOrSignal)
  1158. {
  1159. version (Windows)
  1160. {
  1161. if (codeOrSignal < 0) throw new ProcessException("Invalid exit code");
  1162. version (Win32)
  1163. {
  1164. // On Windows XP, TerminateProcess() appears to terminate the
  1165. // *current* process if it is passed an invalid handle...
  1166. if (pid.osHandle == INVALID_HANDLE_VALUE)
  1167. throw new ProcessException("Invalid process handle");
  1168. }
  1169. if (!TerminateProcess(pid.osHandle, codeOrSignal))
  1170. throw ProcessException.newFromLastError();
  1171. }
  1172. else version (Posix)
  1173. {
  1174. import core.sys.posix.signal;
  1175. if (kill(pid.osHandle, codeOrSignal) == -1)
  1176. throw ProcessException.newFromErrno();
  1177. }
  1178. }
  1179. unittest // tryWait() and kill()
  1180. {
  1181. import core.thread;
  1182. // The test script goes into an infinite loop.
  1183. version (Windows)
  1184. {
  1185. TestScript prog = ":loop
  1186. goto loop";
  1187. }
  1188. else version (Posix)
  1189. {
  1190. import core.sys.posix.signal: SIGTERM, SIGKILL;
  1191. TestScript prog = "while true; do sleep 1; done";
  1192. }
  1193. auto pid = spawnProcess(prog.path);
  1194. Thread.sleep(dur!"seconds"(1));
  1195. kill(pid);
  1196. version (Windows) assert (wait(pid) == 1);
  1197. else version (Posix) assert (wait(pid) == -SIGTERM);
  1198. pid = spawnProcess(prog.path);
  1199. Thread.sleep(dur!"seconds"(1));
  1200. auto s = tryWait(pid);
  1201. assert (!s.terminated && s.status == 0);
  1202. assertThrown!ProcessException(kill(pid, -123)); // Negative code not allowed.
  1203. version (Windows) kill(pid, 123);
  1204. else version (Posix) kill(pid, SIGKILL);
  1205. do { s = tryWait(pid); } while (!s.terminated);
  1206. version (Windows) assert (s.status == 123);
  1207. else version (Posix) assert (s.status == -SIGKILL);
  1208. assertThrown!ProcessException(kill(pid));
  1209. }
  1210. /**
  1211. Creates a unidirectional _pipe.
  1212. Data is written to one end of the _pipe and read from the other.
  1213. ---
  1214. auto p = pipe();
  1215. p.writeEnd.writeln("Hello World");
  1216. assert (p.readEnd.readln().chomp() == "Hello World");
  1217. ---
  1218. Pipes can, for example, be used for interprocess communication
  1219. by spawning a new process and passing one end of the _pipe to
  1220. the child, while the parent uses the other end.
  1221. (See also $(LREF pipeProcess) and $(LREF pipeShell) for an easier
  1222. way of doing this.)
  1223. ---
  1224. // Use cURL to download the dlang.org front page, pipe its
  1225. // output to grep to extract a list of links to ZIP files,
  1226. // and write the list to the file "D downloads.txt":
  1227. auto p = pipe();
  1228. auto outFile = File("D downloads.txt", "w");
  1229. auto cpid = spawnProcess(["curl", "http://dlang.org/download.html"],
  1230. std.stdio.stdin, p.writeEnd);
  1231. scope(exit) wait(cpid);
  1232. auto gpid = spawnProcess(["grep", "-o", `http://\S*\.zip`],
  1233. p.readEnd, outFile);
  1234. scope(exit) wait(gpid);
  1235. ---
  1236. Returns:
  1237. A $(LREF Pipe) object that corresponds to the created _pipe.
  1238. Throws:
  1239. $(XREF stdio,StdioException) on failure.
  1240. */
  1241. version (Posix)
  1242. Pipe pipe() @trusted //TODO: @safe
  1243. {
  1244. int[2] fds;
  1245. if (core.sys.posix.unistd.pipe(fds) != 0)
  1246. throw new StdioException("Unable to create pipe");
  1247. Pipe p;
  1248. auto readFP = fdopen(fds[0], "r");
  1249. if (readFP == null)
  1250. throw new StdioException("Cannot open read end of pipe");
  1251. p._read = File(readFP, null);
  1252. auto writeFP = fdopen(fds[1], "w");
  1253. if (writeFP == null)
  1254. throw new StdioException("Cannot open write end of pipe");
  1255. p._write = File(writeFP, null);
  1256. return p;
  1257. }
  1258. else version (Windows)
  1259. Pipe pipe() @trusted //TODO: @safe
  1260. {
  1261. // use CreatePipe to create an anonymous pipe
  1262. HANDLE readHandle;
  1263. HANDLE writeHandle;
  1264. if (!CreatePipe(&readHandle, &writeHandle, null, 0))
  1265. {
  1266. throw new StdioException(
  1267. "Error creating pipe (" ~ sysErrorString(GetLastError()) ~ ')',
  1268. 0);
  1269. }
  1270. // Create file descriptors from the handles
  1271. version (DMC_RUNTIME)
  1272. {
  1273. auto readFD = _handleToFD(readHandle, FHND_DEVICE);
  1274. auto writeFD = _handleToFD(writeHandle, FHND_DEVICE);
  1275. }
  1276. else // MSVCRT
  1277. {
  1278. auto readFD = _open_osfhandle(readHandle, _O_RDONLY);
  1279. auto writeFD = _open_osfhandle(writeHandle, _O_APPEND);
  1280. }
  1281. version (DMC_RUNTIME) alias .close _close;
  1282. if (readFD == -1 || writeFD == -1)
  1283. {
  1284. // Close file descriptors, then throw.
  1285. if (readFD >= 0) _close(readFD);
  1286. else CloseHandle(readHandle);
  1287. if (writeFD >= 0) _close(writeFD);
  1288. else CloseHandle(writeHandle);
  1289. throw new StdioException("Error creating pipe");
  1290. }
  1291. // Create FILE pointers from the file descriptors
  1292. Pipe p;
  1293. version (DMC_RUNTIME)
  1294. {
  1295. // This is a re-implementation of DMC's fdop…