Process.hx 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /*
  2. * Copyright (C)2005-2018 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package sys.io;
  23. import php.*;
  24. import haxe.io.*;
  25. using StringTools;
  26. using php.Global;
  27. @:forward(iterator)
  28. private abstract ProcessPipes(NativeIndexedArray<Resource>) from NativeIndexedArray<Resource> to NativeIndexedArray<Resource> {
  29. public var stdin (get,never) : Resource;
  30. public var stdout (get,never) : Resource;
  31. public var stderr (get,never) : Resource;
  32. inline function get_stdin() return this[0];
  33. inline function get_stdout() return this[1];
  34. inline function get_stderr() return this[2];
  35. }
  36. private class ReadablePipe extends Input {
  37. var pipe : Resource;
  38. var tmpBytes : Bytes;
  39. public function new(pipe:Resource) {
  40. this.pipe = pipe;
  41. tmpBytes = Bytes.alloc(1);
  42. }
  43. override public function close() : Void {
  44. pipe.fclose();
  45. }
  46. override public function readByte() : Int {
  47. if (readBytes(tmpBytes, 0, 1) == 0) throw Error.Blocked;
  48. return tmpBytes.get(0);
  49. }
  50. override public function readBytes( s:Bytes, pos:Int, len:Int ) : Int {
  51. if(pipe.feof()) throw new Eof();
  52. var result = pipe.fread(len);
  53. if(result == "") throw new Eof();
  54. if(result == false) return throw Error.Custom('Failed to read process output');
  55. var result:String = result;
  56. var bytes = Bytes.ofString(result);
  57. s.blit(pos, bytes, 0, result.length);
  58. return result.length;
  59. }
  60. }
  61. private class WritablePipe extends Output {
  62. var pipe : Resource;
  63. var tmpBytes : Bytes;
  64. public function new(pipe:Resource) {
  65. this.pipe = pipe;
  66. tmpBytes = Bytes.alloc(1);
  67. }
  68. override public function close() : Void {
  69. pipe.fclose();
  70. }
  71. override public function writeByte(c:Int) : Void {
  72. tmpBytes.set(0, c);
  73. writeBytes(tmpBytes, 0, 1);
  74. }
  75. override public function writeBytes( b : Bytes, pos : Int, l : Int ) : Int {
  76. var s = b.getString(pos, l);
  77. if(pipe.feof()) throw new Eof();
  78. var result = Global.fwrite(pipe, s, l);
  79. if(result == false) throw Error.Custom('Failed to write to process input');
  80. return result;
  81. }
  82. }
  83. class Process {
  84. /**
  85. Standard output. The output stream where a process writes its output data.
  86. **/
  87. public var stdout(default, null) : Input;
  88. /**
  89. Standard error. The output stream to output error messages or diagnostics.
  90. **/
  91. public var stderr(default, null) : Input;
  92. /**
  93. Standard input. The stream data going into a process.
  94. **/
  95. public var stdin(default, null) : Output;
  96. var process : Resource;
  97. var pipes : ProcessPipes;
  98. var pid : Int = -1;
  99. var running : Bool = true;
  100. var _exitCode : Int = -1;
  101. /**
  102. Construct a `Process` object, which run the given command immediately.
  103. Command arguments can be passed in two ways: 1. using `args`, 2. appending to `cmd` and leaving `args` as `null`.
  104. 1. When using `args` to pass command arguments, each argument will be automatically quoted, and shell meta-characters will be escaped if needed.
  105. `cmd` should be an executable name that can be located in the `PATH` environment variable, or a path to an executable.
  106. 2. When `args` is not given or is `null`, command arguments can be appended to `cmd`. No automatic quoting/escaping will be performed. `cmd` should be formatted exactly as it would be when typed at the command line.
  107. It can run executables, as well as shell commands that are not executables (e.g. on Windows: `dir`, `cd`, `echo` etc).
  108. `close()` should be called when the `Process` is no longer used.
  109. */
  110. public function new( cmd : String, ?args : Array<String>, ?detached : Bool ) : Void {
  111. if( detached ) throw "Detached process is not supported on this platform";
  112. var descriptors = Syntax.arrayDecl(
  113. Syntax.arrayDecl('pipe', 'r'),
  114. Syntax.arrayDecl('pipe', 'w'),
  115. Syntax.arrayDecl('pipe', 'w')
  116. );
  117. var result = buildCmd(cmd, args).proc_open(descriptors, pipes);
  118. if (result == false) throw Error.Custom('Failed to start process: $cmd');
  119. process = result;
  120. updateStatus();
  121. stdin = new WritablePipe(pipes.stdin);
  122. stdout = new ReadablePipe(pipes.stdout);
  123. stderr = new ReadablePipe(pipes.stderr);
  124. }
  125. /**
  126. Return the process ID.
  127. */
  128. public function getPid() : Int {
  129. return pid;
  130. }
  131. public function exitCode( block : Bool = true ) : Null<Int> {
  132. if(!block) {
  133. updateStatus();
  134. return (running ? null : _exitCode);
  135. }
  136. while (running) {
  137. var arr = Syntax.arrayDecl(process);
  138. Syntax.suppress(Global.stream_select(arr, arr, arr, null));
  139. updateStatus();
  140. }
  141. return _exitCode;
  142. }
  143. /**
  144. Close the process handle and release the associated resources.
  145. All `Process` fields should not be used after `close()` is called.
  146. */
  147. public function close() : Void {
  148. if (!running) return;
  149. for (pipe in pipes) Global.fclose(pipe);
  150. process.proc_close();
  151. }
  152. /**
  153. Kill the process.
  154. */
  155. public function kill() : Void {
  156. process.proc_terminate();
  157. }
  158. function buildCmd( cmd:String, ?args:Array<String> ) : String {
  159. if (args == null) return cmd;
  160. return switch (Sys.systemName()) {
  161. case "Windows":
  162. [cmd.replace("/", "\\")].concat(args).map(StringTools.quoteWinArg.bind(_, true)).join(" ");
  163. case _:
  164. [cmd].concat(args).map(StringTools.quoteUnixArg).join(" ");
  165. }
  166. }
  167. function updateStatus() : Void {
  168. if (!running) return;
  169. var status = process.proc_get_status();
  170. if (status == false) throw Error.Custom('Failed to obtain process status');
  171. var status:NativeAssocArray<Scalar> = status;
  172. pid = status['pid'];
  173. running = status['running'];
  174. _exitCode = status['exitcode'];
  175. }
  176. }