osproc.nim 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements an advanced facility for executing OS processes
  10. ## and process communication.
  11. ##
  12. ## **See also:**
  13. ## * `os module <os.html>`_
  14. ## * `streams module <streams.html>`_
  15. ## * `memfiles module <memfiles.html>`_
  16. include "system/inclrtl"
  17. import
  18. strutils, os, strtabs, streams, cpuinfo, streamwrapper,
  19. std/private/since
  20. export quoteShell, quoteShellWindows, quoteShellPosix
  21. when defined(windows):
  22. import winlean
  23. else:
  24. import posix
  25. when defined(linux) and defined(useClone):
  26. import linux
  27. when defined(nimPreviewSlimSystem):
  28. import std/[syncio, assertions]
  29. when defined(windows):
  30. import std/widestrs
  31. type
  32. ProcessOption* = enum ## Options that can be passed to `startProcess proc
  33. ## <#startProcess,string,string,openArray[string],StringTableRef,set[ProcessOption]>`_.
  34. poEchoCmd, ## Echo the command before execution.
  35. poUsePath, ## Asks system to search for executable using PATH environment
  36. ## variable.
  37. ## On Windows, this is the default.
  38. poEvalCommand, ## Pass `command` directly to the shell, without quoting.
  39. ## Use it only if `command` comes from trusted source.
  40. poStdErrToStdOut, ## Merge stdout and stderr to the stdout stream.
  41. poParentStreams, ## Use the parent's streams.
  42. poInteractive, ## Optimize the buffer handling for responsiveness for
  43. ## UI applications. Currently this only affects
  44. ## Windows: Named pipes are used so that you can peek
  45. ## at the process' output streams.
  46. poDaemon ## Windows: The program creates no Window.
  47. ## Unix: Start the program as a daemon. This is still
  48. ## work in progress!
  49. ProcessObj = object of RootObj
  50. when defined(windows):
  51. fProcessHandle: Handle
  52. fThreadHandle: Handle
  53. inHandle, outHandle, errHandle: FileHandle
  54. id: Handle
  55. else:
  56. inHandle, outHandle, errHandle: FileHandle
  57. id: Pid
  58. inStream, outStream, errStream: owned(Stream)
  59. exitStatus: cint
  60. exitFlag: bool
  61. options: set[ProcessOption]
  62. Process* = ref ProcessObj ## Represents an operating system process.
  63. proc execProcess*(command: string, workingDir: string = "",
  64. args: openArray[string] = [], env: StringTableRef = nil,
  65. options: set[ProcessOption] = {poStdErrToStdOut, poUsePath, poEvalCommand}):
  66. string {.rtl, extern: "nosp$1",
  67. tags: [ExecIOEffect, ReadIOEffect, RootEffect].}
  68. ## A convenience procedure that executes ``command`` with ``startProcess``
  69. ## and returns its output as a string.
  70. ##
  71. ## .. warning:: This function uses `poEvalCommand` by default for backwards
  72. ## compatibility. Make sure to pass options explicitly.
  73. ##
  74. ## See also:
  75. ## * `startProcess proc
  76. ## <#startProcess,string,string,openArray[string],StringTableRef,set[ProcessOption]>`_
  77. ## * `execProcesses proc <#execProcesses,openArray[string],proc(int),proc(int,Process)>`_
  78. ## * `execCmd proc <#execCmd,string>`_
  79. ##
  80. ## Example:
  81. ##
  82. ## .. code-block:: Nim
  83. ## let outp = execProcess("nim", args=["c", "-r", "mytestfile.nim"], options={poUsePath})
  84. ## let outp_shell = execProcess("nim c -r mytestfile.nim")
  85. ## # Note: outp may have an interleave of text from the nim compile
  86. ## # and any output from mytestfile when it runs
  87. proc execCmd*(command: string): int {.rtl, extern: "nosp$1",
  88. tags: [ExecIOEffect, ReadIOEffect, RootEffect].}
  89. ## Executes ``command`` and returns its error code.
  90. ##
  91. ## Standard input, output, error streams are inherited from the calling process.
  92. ## This operation is also often called `system`:idx:.
  93. ##
  94. ## See also:
  95. ## * `execCmdEx proc <#execCmdEx,string,set[ProcessOption],StringTableRef,string,string>`_
  96. ## * `startProcess proc
  97. ## <#startProcess,string,string,openArray[string],StringTableRef,set[ProcessOption]>`_
  98. ## * `execProcess proc
  99. ## <#execProcess,string,string,openArray[string],StringTableRef,set[ProcessOption]>`_
  100. ##
  101. ## Example:
  102. ##
  103. ## .. code-block:: Nim
  104. ## let errC = execCmd("nim c -r mytestfile.nim")
  105. proc startProcess*(command: string, workingDir: string = "",
  106. args: openArray[string] = [], env: StringTableRef = nil,
  107. options: set[ProcessOption] = {poStdErrToStdOut}):
  108. owned(Process) {.rtl, extern: "nosp$1",
  109. tags: [ExecIOEffect, ReadEnvEffect, RootEffect].}
  110. ## Starts a process. `Command` is the executable file, `workingDir` is the
  111. ## process's working directory. If ``workingDir == ""`` the current directory
  112. ## is used (default). `args` are the command line arguments that are passed to the
  113. ## process. On many operating systems, the first command line argument is the
  114. ## name of the executable. `args` should *not* contain this argument!
  115. ## `env` is the environment that will be passed to the process.
  116. ## If ``env == nil`` (default) the environment is inherited of
  117. ## the parent process. `options` are additional flags that may be passed
  118. ## to `startProcess`. See the documentation of `ProcessOption<#ProcessOption>`_
  119. ## for the meaning of these flags.
  120. ##
  121. ## You need to `close <#close,Process>`_ the process when done.
  122. ##
  123. ## Note that you can't pass any `args` if you use the option
  124. ## ``poEvalCommand``, which invokes the system shell to run the specified
  125. ## `command`. In this situation you have to concatenate manually the contents
  126. ## of `args` to `command` carefully escaping/quoting any special characters,
  127. ## since it will be passed *as is* to the system shell. Each system/shell may
  128. ## feature different escaping rules, so try to avoid this kind of shell
  129. ## invocation if possible as it leads to non portable software.
  130. ##
  131. ## Return value: The newly created process object. Nil is never returned,
  132. ## but ``OSError`` is raised in case of an error.
  133. ##
  134. ## See also:
  135. ## * `execProcesses proc <#execProcesses,openArray[string],proc(int),proc(int,Process)>`_
  136. ## * `execProcess proc
  137. ## <#execProcess,string,string,openArray[string],StringTableRef,set[ProcessOption]>`_
  138. ## * `execCmd proc <#execCmd,string>`_
  139. proc close*(p: Process) {.rtl, extern: "nosp$1", tags: [WriteIOEffect].}
  140. ## When the process has finished executing, cleanup related handles.
  141. ##
  142. ## .. warning:: If the process has not finished executing, this will forcibly
  143. ## terminate the process. Doing so may result in zombie processes and
  144. ## `pty leaks <http://stackoverflow.com/questions/27021641/how-to-fix-request-failed-on-channel-0>`_.
  145. proc suspend*(p: Process) {.rtl, extern: "nosp$1", tags: [].}
  146. ## Suspends the process `p`.
  147. ##
  148. ## See also:
  149. ## * `resume proc <#resume,Process>`_
  150. ## * `terminate proc <#terminate,Process>`_
  151. ## * `kill proc <#kill,Process>`_
  152. proc resume*(p: Process) {.rtl, extern: "nosp$1", tags: [].}
  153. ## Resumes the process `p`.
  154. ##
  155. ## See also:
  156. ## * `suspend proc <#suspend,Process>`_
  157. ## * `terminate proc <#terminate,Process>`_
  158. ## * `kill proc <#kill,Process>`_
  159. proc terminate*(p: Process) {.rtl, extern: "nosp$1", tags: [].}
  160. ## Stop the process `p`.
  161. ##
  162. ## On Posix OSes the procedure sends ``SIGTERM`` to the process.
  163. ## On Windows the Win32 API function ``TerminateProcess()``
  164. ## is called to stop the process.
  165. ##
  166. ## See also:
  167. ## * `suspend proc <#suspend,Process>`_
  168. ## * `resume proc <#resume,Process>`_
  169. ## * `kill proc <#kill,Process>`_
  170. ## * `posix_utils.sendSignal(pid: Pid, signal: int) <posix_utils.html#sendSignal,Pid,int>`_
  171. proc kill*(p: Process) {.rtl, extern: "nosp$1", tags: [].}
  172. ## Kill the process `p`.
  173. ##
  174. ## On Posix OSes the procedure sends ``SIGKILL`` to the process.
  175. ## On Windows ``kill`` is simply an alias for `terminate() <#terminate,Process>`_.
  176. ##
  177. ## See also:
  178. ## * `suspend proc <#suspend,Process>`_
  179. ## * `resume proc <#resume,Process>`_
  180. ## * `terminate proc <#terminate,Process>`_
  181. ## * `posix_utils.sendSignal(pid: Pid, signal: int) <posix_utils.html#sendSignal,Pid,int>`_
  182. proc running*(p: Process): bool {.rtl, extern: "nosp$1", tags: [].}
  183. ## Returns true if the process `p` is still running. Returns immediately.
  184. proc processID*(p: Process): int {.rtl, extern: "nosp$1".} =
  185. ## Returns `p`'s process ID.
  186. ##
  187. ## See also:
  188. ## * `os.getCurrentProcessId proc <os.html#getCurrentProcessId>`_
  189. return p.id
  190. proc waitForExit*(p: Process, timeout: int = -1): int {.rtl,
  191. extern: "nosp$1", tags: [].}
  192. ## Waits for the process to finish and returns `p`'s error code.
  193. ##
  194. ## .. warning:: Be careful when using `waitForExit` for processes created without
  195. ## `poParentStreams` because they may fill output buffers, causing deadlock.
  196. ##
  197. ## On posix, if the process has exited because of a signal, 128 + signal
  198. ## number will be returned.
  199. proc peekExitCode*(p: Process): int {.rtl, extern: "nosp$1", tags: [].}
  200. ## Return `-1` if the process is still running. Otherwise the process' exit code.
  201. ##
  202. ## On posix, if the process has exited because of a signal, 128 + signal
  203. ## number will be returned.
  204. proc inputStream*(p: Process): Stream {.rtl, extern: "nosp$1", tags: [].}
  205. ## Returns ``p``'s input stream for writing to.
  206. ##
  207. ## .. warning:: The returned `Stream` should not be closed manually as it
  208. ## is closed when closing the Process ``p``.
  209. ##
  210. ## See also:
  211. ## * `outputStream proc <#outputStream,Process>`_
  212. ## * `errorStream proc <#errorStream,Process>`_
  213. proc outputStream*(p: Process): Stream {.rtl, extern: "nosp$1", tags: [].}
  214. ## Returns ``p``'s output stream for reading from.
  215. ##
  216. ## You cannot perform peek/write/setOption operations to this stream.
  217. ## Use `peekableOutputStream proc <#peekableOutputStream,Process>`_
  218. ## if you need to peek stream.
  219. ##
  220. ## .. warning:: The returned `Stream` should not be closed manually as it
  221. ## is closed when closing the Process ``p``.
  222. ##
  223. ## See also:
  224. ## * `inputStream proc <#inputStream,Process>`_
  225. ## * `errorStream proc <#errorStream,Process>`_
  226. proc errorStream*(p: Process): Stream {.rtl, extern: "nosp$1", tags: [].}
  227. ## Returns ``p``'s error stream for reading from.
  228. ##
  229. ## You cannot perform peek/write/setOption operations to this stream.
  230. ## Use `peekableErrorStream proc <#peekableErrorStream,Process>`_
  231. ## if you need to peek stream.
  232. ##
  233. ## .. warning:: The returned `Stream` should not be closed manually as it
  234. ## is closed when closing the Process ``p``.
  235. ##
  236. ## See also:
  237. ## * `inputStream proc <#inputStream,Process>`_
  238. ## * `outputStream proc <#outputStream,Process>`_
  239. proc peekableOutputStream*(p: Process): Stream {.rtl, extern: "nosp$1", tags: [], since: (1, 3).}
  240. ## Returns ``p``'s output stream for reading from.
  241. ##
  242. ## You can peek returned stream.
  243. ##
  244. ## .. warning:: The returned `Stream` should not be closed manually as it
  245. ## is closed when closing the Process ``p``.
  246. ##
  247. ## See also:
  248. ## * `outputStream proc <#outputStream,Process>`_
  249. ## * `peekableErrorStream proc <#peekableErrorStream,Process>`_
  250. proc peekableErrorStream*(p: Process): Stream {.rtl, extern: "nosp$1", tags: [], since: (1, 3).}
  251. ## Returns ``p``'s error stream for reading from.
  252. ##
  253. ## You can run peek operation to returned stream.
  254. ##
  255. ## .. warning:: The returned `Stream` should not be closed manually as it
  256. ## is closed when closing the Process ``p``.
  257. ##
  258. ## See also:
  259. ## * `errorStream proc <#errorStream,Process>`_
  260. ## * `peekableOutputStream proc <#peekableOutputStream,Process>`_
  261. proc inputHandle*(p: Process): FileHandle {.rtl, extern: "nosp$1",
  262. tags: [].} =
  263. ## Returns ``p``'s input file handle for writing to.
  264. ##
  265. ## .. warning:: The returned `FileHandle` should not be closed manually as
  266. ## it is closed when closing the Process ``p``.
  267. ##
  268. ## See also:
  269. ## * `outputHandle proc <#outputHandle,Process>`_
  270. ## * `errorHandle proc <#errorHandle,Process>`_
  271. result = p.inHandle
  272. proc outputHandle*(p: Process): FileHandle {.rtl, extern: "nosp$1",
  273. tags: [].} =
  274. ## Returns ``p``'s output file handle for reading from.
  275. ##
  276. ## .. warning:: The returned `FileHandle` should not be closed manually as
  277. ## it is closed when closing the Process ``p``.
  278. ##
  279. ## See also:
  280. ## * `inputHandle proc <#inputHandle,Process>`_
  281. ## * `errorHandle proc <#errorHandle,Process>`_
  282. result = p.outHandle
  283. proc errorHandle*(p: Process): FileHandle {.rtl, extern: "nosp$1",
  284. tags: [].} =
  285. ## Returns ``p``'s error file handle for reading from.
  286. ##
  287. ## .. warning:: The returned `FileHandle` should not be closed manually as
  288. ## it is closed when closing the Process ``p``.
  289. ##
  290. ## See also:
  291. ## * `inputHandle proc <#inputHandle,Process>`_
  292. ## * `outputHandle proc <#outputHandle,Process>`_
  293. result = p.errHandle
  294. proc countProcessors*(): int {.rtl, extern: "nosp$1".} =
  295. ## Returns the number of the processors/cores the machine has.
  296. ## Returns 0 if it cannot be detected.
  297. ## It is implemented just calling `cpuinfo.countProcessors`.
  298. result = cpuinfo.countProcessors()
  299. when not defined(nimHasEffectsOf):
  300. {.pragma: effectsOf.}
  301. proc execProcesses*(cmds: openArray[string],
  302. options = {poStdErrToStdOut, poParentStreams}, n = countProcessors(),
  303. beforeRunEvent: proc(idx: int) = nil,
  304. afterRunEvent: proc(idx: int, p: Process) = nil):
  305. int {.rtl, extern: "nosp$1",
  306. tags: [ExecIOEffect, TimeEffect, ReadEnvEffect, RootEffect],
  307. effectsOf: [beforeRunEvent, afterRunEvent].} =
  308. ## Executes the commands `cmds` in parallel.
  309. ## Creates `n` processes that execute in parallel.
  310. ##
  311. ## The highest (absolute) return value of all processes is returned.
  312. ## Runs `beforeRunEvent` before running each command.
  313. assert n > 0
  314. if n > 1:
  315. var i = 0
  316. var q = newSeq[Process](n)
  317. var idxs = newSeq[int](n) # map process index to cmds index
  318. when defined(windows):
  319. var w: WOHandleArray
  320. var m = min(min(n, MAXIMUM_WAIT_OBJECTS), cmds.len)
  321. var wcount = m
  322. else:
  323. var m = min(n, cmds.len)
  324. while i < m:
  325. if beforeRunEvent != nil:
  326. beforeRunEvent(i)
  327. q[i] = startProcess(cmds[i], options = options + {poEvalCommand})
  328. idxs[i] = i
  329. when defined(windows):
  330. w[i] = q[i].fProcessHandle
  331. inc(i)
  332. var ecount = len(cmds)
  333. while ecount > 0:
  334. var rexit = -1
  335. when defined(windows):
  336. # waiting for all children, get result if any child exits
  337. var ret = waitForMultipleObjects(int32(wcount), addr(w), 0'i32,
  338. INFINITE)
  339. if ret == WAIT_TIMEOUT:
  340. # must not be happen
  341. discard
  342. elif ret == WAIT_FAILED:
  343. raiseOSError(osLastError())
  344. else:
  345. var status: int32
  346. for r in 0..m-1:
  347. if not isNil(q[r]) and q[r].fProcessHandle == w[ret]:
  348. discard getExitCodeProcess(q[r].fProcessHandle, status)
  349. q[r].exitFlag = true
  350. q[r].exitStatus = status
  351. rexit = r
  352. break
  353. else:
  354. var status: cint = 1
  355. # waiting for all children, get result if any child exits
  356. let res = waitpid(-1, status, 0)
  357. if res > 0:
  358. for r in 0..m-1:
  359. if not isNil(q[r]) and q[r].id == res:
  360. if WIFEXITED(status) or WIFSIGNALED(status):
  361. q[r].exitFlag = true
  362. q[r].exitStatus = status
  363. rexit = r
  364. break
  365. else:
  366. let err = osLastError()
  367. if err == OSErrorCode(ECHILD):
  368. # some child exits, we need to check our childs exit codes
  369. for r in 0..m-1:
  370. if (not isNil(q[r])) and (not running(q[r])):
  371. q[r].exitFlag = true
  372. q[r].exitStatus = status
  373. rexit = r
  374. break
  375. elif err == OSErrorCode(EINTR):
  376. # signal interrupted our syscall, lets repeat it
  377. continue
  378. else:
  379. # all other errors are exceptions
  380. raiseOSError(err)
  381. if rexit >= 0:
  382. when defined(windows):
  383. let processHandle = q[rexit].fProcessHandle
  384. result = max(result, abs(q[rexit].peekExitCode()))
  385. if afterRunEvent != nil: afterRunEvent(idxs[rexit], q[rexit])
  386. close(q[rexit])
  387. if i < len(cmds):
  388. if beforeRunEvent != nil: beforeRunEvent(i)
  389. q[rexit] = startProcess(cmds[i],
  390. options = options + {poEvalCommand})
  391. idxs[rexit] = i
  392. when defined(windows):
  393. w[rexit] = q[rexit].fProcessHandle
  394. inc(i)
  395. else:
  396. when defined(windows):
  397. for k in 0..wcount - 1:
  398. if w[k] == processHandle:
  399. w[k] = w[wcount - 1]
  400. w[wcount - 1] = 0
  401. dec(wcount)
  402. break
  403. q[rexit] = nil
  404. dec(ecount)
  405. else:
  406. for i in 0..high(cmds):
  407. if beforeRunEvent != nil:
  408. beforeRunEvent(i)
  409. var p = startProcess(cmds[i], options = options + {poEvalCommand})
  410. result = max(abs(waitForExit(p)), result)
  411. if afterRunEvent != nil: afterRunEvent(i, p)
  412. close(p)
  413. iterator lines*(p: Process, keepNewLines = false): string {.since: (1, 3), tags: [ReadIOEffect].} =
  414. ## Convenience iterator for working with `startProcess` to read data from a
  415. ## background process.
  416. ##
  417. ## See also:
  418. ## * `readLines proc <#readLines,Process>`_
  419. ##
  420. ## Example:
  421. ##
  422. ## .. code-block:: Nim
  423. ## const opts = {poUsePath, poDaemon, poStdErrToStdOut}
  424. ## var ps: seq[Process]
  425. ## for prog in ["a", "b"]: # run 2 progs in parallel
  426. ## ps.add startProcess("nim", "", ["r", prog], nil, opts)
  427. ## for p in ps:
  428. ## var i = 0
  429. ## for line in p.lines:
  430. ## echo line
  431. ## i.inc
  432. ## if i > 100: break
  433. ## p.close
  434. var outp = p.outputStream
  435. var line = newStringOfCap(120)
  436. while outp.readLine(line):
  437. if keepNewLines:
  438. line.add("\n")
  439. yield line
  440. discard waitForExit(p)
  441. proc readLines*(p: Process): (seq[string], int) {.since: (1, 3).} =
  442. ## Convenience function for working with `startProcess` to read data from a
  443. ## background process.
  444. ##
  445. ## See also:
  446. ## * `lines iterator <#lines.i,Process>`_
  447. ##
  448. ## Example:
  449. ##
  450. ## .. code-block:: Nim
  451. ## const opts = {poUsePath, poDaemon, poStdErrToStdOut}
  452. ## var ps: seq[Process]
  453. ## for prog in ["a", "b"]: # run 2 progs in parallel
  454. ## ps.add startProcess("nim", "", ["r", prog], nil, opts)
  455. ## for p in ps:
  456. ## let (lines, exCode) = p.readLines
  457. ## if exCode != 0:
  458. ## for line in lines: echo line
  459. ## p.close
  460. for line in p.lines: result[0].add(line)
  461. result[1] = p.peekExitCode
  462. when not defined(useNimRtl):
  463. proc execProcess(command: string, workingDir: string = "",
  464. args: openArray[string] = [], env: StringTableRef = nil,
  465. options: set[ProcessOption] = {poStdErrToStdOut, poUsePath,
  466. poEvalCommand}):
  467. string =
  468. var p = startProcess(command, workingDir = workingDir, args = args,
  469. env = env, options = options)
  470. var outp = outputStream(p)
  471. result = ""
  472. var line = newStringOfCap(120)
  473. # consider `p.lines(keepNewLines=true)` to circumvent `running` busy-wait
  474. while true:
  475. # FIXME: converts CR-LF to LF.
  476. if outp.readLine(line):
  477. result.add(line)
  478. result.add("\n")
  479. elif not running(p): break
  480. close(p)
  481. template streamAccess(p) =
  482. assert poParentStreams notin p.options, "API usage error: stream access not allowed when you use poParentStreams"
  483. when defined(windows) and not defined(useNimRtl):
  484. # We need to implement a handle stream for Windows:
  485. type
  486. FileHandleStream = ref object of StreamObj
  487. handle: Handle
  488. atTheEnd: bool
  489. proc closeHandleCheck(handle: Handle) {.inline.} =
  490. if handle.closeHandle() == 0:
  491. raiseOSError(osLastError())
  492. proc fileClose[T: Handle | FileHandle](h: var T) {.inline.} =
  493. if h > 4:
  494. closeHandleCheck(h)
  495. h = INVALID_HANDLE_VALUE.T
  496. proc hsClose(s: Stream) =
  497. FileHandleStream(s).handle.fileClose()
  498. proc hsAtEnd(s: Stream): bool = return FileHandleStream(s).atTheEnd
  499. proc hsReadData(s: Stream, buffer: pointer, bufLen: int): int =
  500. var s = FileHandleStream(s)
  501. if s.atTheEnd: return 0
  502. var br: int32
  503. var a = winlean.readFile(s.handle, buffer, bufLen.cint, addr br, nil)
  504. # TRUE and zero bytes returned (EOF).
  505. # TRUE and n (>0) bytes returned (good data).
  506. # FALSE and bytes returned undefined (system error).
  507. if a == 0 and br != 0: raiseOSError(osLastError())
  508. s.atTheEnd = br == 0 #< bufLen
  509. result = br
  510. proc hsWriteData(s: Stream, buffer: pointer, bufLen: int) =
  511. var s = FileHandleStream(s)
  512. var bytesWritten: int32
  513. var a = winlean.writeFile(s.handle, buffer, bufLen.cint,
  514. addr bytesWritten, nil)
  515. if a == 0: raiseOSError(osLastError())
  516. proc newFileHandleStream(handle: Handle): owned FileHandleStream =
  517. new(result)
  518. result.handle = handle
  519. result.closeImpl = hsClose
  520. result.atEndImpl = hsAtEnd
  521. result.readDataImpl = hsReadData
  522. result.writeDataImpl = hsWriteData
  523. proc buildCommandLine(a: string, args: openArray[string]): string =
  524. result = quoteShell(a)
  525. for i in 0..high(args):
  526. result.add(' ')
  527. result.add(quoteShell(args[i]))
  528. proc buildEnv(env: StringTableRef): tuple[str: cstring, len: int] =
  529. var L = 0
  530. for key, val in pairs(env): inc(L, key.len + val.len + 2)
  531. var str = cast[cstring](alloc0(L+2))
  532. L = 0
  533. for key, val in pairs(env):
  534. var x = key & "=" & val
  535. copyMem(addr(str[L]), cstring(x), x.len+1) # copy \0
  536. inc(L, x.len+1)
  537. (str, L)
  538. #proc open_osfhandle(osh: Handle, mode: int): int {.
  539. # importc: "_open_osfhandle", header: "<fcntl.h>".}
  540. #var
  541. # O_WRONLY {.importc: "_O_WRONLY", header: "<fcntl.h>".}: int
  542. # O_RDONLY {.importc: "_O_RDONLY", header: "<fcntl.h>".}: int
  543. proc myDup(h: Handle; inherit: WINBOOL = 1): Handle =
  544. let thisProc = getCurrentProcess()
  545. if duplicateHandle(thisProc, h, thisProc, addr result, 0, inherit,
  546. DUPLICATE_SAME_ACCESS) == 0:
  547. raiseOSError(osLastError())
  548. proc createAllPipeHandles(si: var STARTUPINFO;
  549. stdin, stdout, stderr: var Handle; hash: int) =
  550. var sa: SECURITY_ATTRIBUTES
  551. sa.nLength = sizeof(SECURITY_ATTRIBUTES).cint
  552. sa.lpSecurityDescriptor = nil
  553. sa.bInheritHandle = 1
  554. let pipeOutName = newWideCString(r"\\.\pipe\stdout" & $hash)
  555. let pipeInName = newWideCString(r"\\.\pipe\stdin" & $hash)
  556. let pipeOut = createNamedPipe(pipeOutName,
  557. dwOpenMode = PIPE_ACCESS_INBOUND or FILE_FLAG_WRITE_THROUGH,
  558. dwPipeMode = PIPE_NOWAIT,
  559. nMaxInstances = 1,
  560. nOutBufferSize = 1024, nInBufferSize = 1024,
  561. nDefaultTimeOut = 0, addr sa)
  562. if pipeOut == INVALID_HANDLE_VALUE:
  563. raiseOSError(osLastError())
  564. let pipeIn = createNamedPipe(pipeInName,
  565. dwOpenMode = PIPE_ACCESS_OUTBOUND or FILE_FLAG_WRITE_THROUGH,
  566. dwPipeMode = PIPE_NOWAIT,
  567. nMaxInstances = 1,
  568. nOutBufferSize = 1024, nInBufferSize = 1024,
  569. nDefaultTimeOut = 0, addr sa)
  570. if pipeIn == INVALID_HANDLE_VALUE:
  571. raiseOSError(osLastError())
  572. si.hStdOutput = createFileW(pipeOutName,
  573. FILE_WRITE_DATA or SYNCHRONIZE, 0, addr sa,
  574. OPEN_EXISTING, # very important flag!
  575. FILE_ATTRIBUTE_NORMAL,
  576. 0 # no template file for OPEN_EXISTING
  577. )
  578. if si.hStdOutput == INVALID_HANDLE_VALUE:
  579. raiseOSError(osLastError())
  580. si.hStdError = myDup(si.hStdOutput)
  581. si.hStdInput = createFileW(pipeInName,
  582. FILE_READ_DATA or SYNCHRONIZE, 0, addr sa,
  583. OPEN_EXISTING, # very important flag!
  584. FILE_ATTRIBUTE_NORMAL,
  585. 0 # no template file for OPEN_EXISTING
  586. )
  587. if si.hStdInput == INVALID_HANDLE_VALUE:
  588. raiseOSError(osLastError())
  589. stdin = myDup(pipeIn, 0)
  590. stdout = myDup(pipeOut, 0)
  591. closeHandleCheck(pipeIn)
  592. closeHandleCheck(pipeOut)
  593. stderr = stdout
  594. proc createPipeHandles(rdHandle, wrHandle: var Handle) =
  595. var sa: SECURITY_ATTRIBUTES
  596. sa.nLength = sizeof(SECURITY_ATTRIBUTES).cint
  597. sa.lpSecurityDescriptor = nil
  598. sa.bInheritHandle = 1
  599. if createPipe(rdHandle, wrHandle, sa, 0) == 0'i32:
  600. raiseOSError(osLastError())
  601. proc startProcess(command: string, workingDir: string = "",
  602. args: openArray[string] = [], env: StringTableRef = nil,
  603. options: set[ProcessOption] = {poStdErrToStdOut}):
  604. owned Process =
  605. var
  606. si: STARTUPINFO
  607. procInfo: PROCESS_INFORMATION
  608. success: int
  609. hi, ho, he: Handle
  610. new(result)
  611. result.options = options
  612. result.exitFlag = true
  613. si.cb = sizeof(si).cint
  614. if poParentStreams notin options:
  615. si.dwFlags = STARTF_USESTDHANDLES # STARTF_USESHOWWINDOW or
  616. if poInteractive notin options:
  617. createPipeHandles(si.hStdInput, hi)
  618. createPipeHandles(ho, si.hStdOutput)
  619. if poStdErrToStdOut in options:
  620. si.hStdError = si.hStdOutput
  621. he = ho
  622. else:
  623. createPipeHandles(he, si.hStdError)
  624. if setHandleInformation(he, DWORD(1), DWORD(0)) == 0'i32:
  625. raiseOSError(osLastError())
  626. if setHandleInformation(hi, DWORD(1), DWORD(0)) == 0'i32:
  627. raiseOSError(osLastError())
  628. if setHandleInformation(ho, DWORD(1), DWORD(0)) == 0'i32:
  629. raiseOSError(osLastError())
  630. else:
  631. createAllPipeHandles(si, hi, ho, he, cast[int](result))
  632. result.inHandle = FileHandle(hi)
  633. result.outHandle = FileHandle(ho)
  634. result.errHandle = FileHandle(he)
  635. else:
  636. si.hStdError = getStdHandle(STD_ERROR_HANDLE)
  637. si.hStdInput = getStdHandle(STD_INPUT_HANDLE)
  638. si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE)
  639. result.inHandle = FileHandle(si.hStdInput)
  640. result.outHandle = FileHandle(si.hStdOutput)
  641. result.errHandle = FileHandle(si.hStdError)
  642. var cmdl: cstring
  643. var cmdRoot: string
  644. if poEvalCommand in options:
  645. cmdl = command
  646. assert args.len == 0
  647. else:
  648. cmdRoot = buildCommandLine(command, args)
  649. cmdl = cstring(cmdRoot)
  650. var wd: cstring = nil
  651. var e = (str: nil.cstring, len: -1)
  652. if len(workingDir) > 0: wd = workingDir
  653. if env != nil: e = buildEnv(env)
  654. if poEchoCmd in options: echo($cmdl)
  655. when useWinUnicode:
  656. var tmp = newWideCString(cmdl)
  657. var ee =
  658. if e.str.isNil: newWideCString(cstring(nil))
  659. else: newWideCString(e.str, e.len)
  660. var wwd = newWideCString(wd)
  661. var flags = NORMAL_PRIORITY_CLASS or CREATE_UNICODE_ENVIRONMENT
  662. if poDaemon in options: flags = flags or CREATE_NO_WINDOW
  663. success = winlean.createProcessW(nil, tmp, nil, nil, 1, flags,
  664. ee, wwd, si, procInfo)
  665. else:
  666. var ee =
  667. if e.str.isNil: cstring(nil)
  668. else: cstring(e.str)
  669. success = winlean.createProcessA(nil,
  670. cmdl, nil, nil, 1, NORMAL_PRIORITY_CLASS, ee, wd, si, procInfo)
  671. let lastError = osLastError()
  672. if poParentStreams notin options:
  673. fileClose(si.hStdInput)
  674. fileClose(si.hStdOutput)
  675. if poStdErrToStdOut notin options:
  676. fileClose(si.hStdError)
  677. if e.str != nil: dealloc(e.str)
  678. if success == 0:
  679. if poInteractive in result.options: close(result)
  680. const errInvalidParameter = 87.int
  681. const errFileNotFound = 2.int
  682. if lastError.int in {errInvalidParameter, errFileNotFound}:
  683. raiseOSError(lastError,
  684. "Requested command not found: '$1'. OS error:" % command)
  685. else:
  686. raiseOSError(lastError, command)
  687. result.fProcessHandle = procInfo.hProcess
  688. result.fThreadHandle = procInfo.hThread
  689. result.id = procInfo.dwProcessId
  690. result.exitFlag = false
  691. proc closeThreadAndProcessHandle(p: Process) =
  692. if p.fThreadHandle != 0:
  693. closeHandleCheck(p.fThreadHandle)
  694. p.fThreadHandle = 0
  695. if p.fProcessHandle != 0:
  696. closeHandleCheck(p.fProcessHandle)
  697. p.fProcessHandle = 0
  698. proc close(p: Process) =
  699. if poParentStreams notin p.options:
  700. if p.inStream == nil:
  701. p.inHandle.fileClose()
  702. else:
  703. # p.inHandle can be already closed via inputStream.
  704. p.inStream.close
  705. # You may NOT close outputStream and errorStream.
  706. assert p.outStream == nil or FileHandleStream(p.outStream).handle != INVALID_HANDLE_VALUE
  707. assert p.errStream == nil or FileHandleStream(p.errStream).handle != INVALID_HANDLE_VALUE
  708. if p.outHandle != p.errHandle:
  709. p.errHandle.fileClose()
  710. p.outHandle.fileClose()
  711. p.closeThreadAndProcessHandle()
  712. proc suspend(p: Process) =
  713. discard suspendThread(p.fThreadHandle)
  714. proc resume(p: Process) =
  715. discard resumeThread(p.fThreadHandle)
  716. proc running(p: Process): bool =
  717. if p.exitFlag:
  718. return false
  719. else:
  720. var x = waitForSingleObject(p.fProcessHandle, 0)
  721. return x == WAIT_TIMEOUT
  722. proc terminate(p: Process) =
  723. if running(p):
  724. discard terminateProcess(p.fProcessHandle, 0)
  725. proc kill(p: Process) =
  726. terminate(p)
  727. proc waitForExit(p: Process, timeout: int = -1): int =
  728. if p.exitFlag:
  729. return p.exitStatus
  730. let res = waitForSingleObject(p.fProcessHandle, timeout.int32)
  731. if res == WAIT_TIMEOUT:
  732. terminate(p)
  733. var status: int32
  734. discard getExitCodeProcess(p.fProcessHandle, status)
  735. if status != STILL_ACTIVE:
  736. p.exitFlag = true
  737. p.exitStatus = status
  738. p.closeThreadAndProcessHandle()
  739. result = status
  740. else:
  741. result = -1
  742. proc peekExitCode(p: Process): int =
  743. if p.exitFlag:
  744. return p.exitStatus
  745. result = -1
  746. var b = waitForSingleObject(p.fProcessHandle, 0) == WAIT_TIMEOUT
  747. if not b:
  748. var status: int32
  749. discard getExitCodeProcess(p.fProcessHandle, status)
  750. p.exitFlag = true
  751. p.exitStatus = status
  752. p.closeThreadAndProcessHandle()
  753. result = status
  754. proc inputStream(p: Process): Stream =
  755. streamAccess(p)
  756. if p.inStream == nil:
  757. p.inStream = newFileHandleStream(p.inHandle)
  758. result = p.inStream
  759. proc outputStream(p: Process): Stream =
  760. streamAccess(p)
  761. if p.outStream == nil:
  762. p.outStream = newFileHandleStream(p.outHandle)
  763. result = p.outStream
  764. proc errorStream(p: Process): Stream =
  765. streamAccess(p)
  766. if p.errStream == nil:
  767. p.errStream = newFileHandleStream(p.errHandle)
  768. result = p.errStream
  769. proc peekableOutputStream(p: Process): Stream =
  770. streamAccess(p)
  771. if p.outStream == nil:
  772. p.outStream = newFileHandleStream(p.outHandle).newPipeOutStream
  773. result = p.outStream
  774. proc peekableErrorStream(p: Process): Stream =
  775. streamAccess(p)
  776. if p.errStream == nil:
  777. p.errStream = newFileHandleStream(p.errHandle).newPipeOutStream
  778. result = p.errStream
  779. proc execCmd(command: string): int =
  780. var
  781. si: STARTUPINFO
  782. procInfo: PROCESS_INFORMATION
  783. process: Handle
  784. L: int32
  785. si.cb = sizeof(si).cint
  786. si.hStdError = getStdHandle(STD_ERROR_HANDLE)
  787. si.hStdInput = getStdHandle(STD_INPUT_HANDLE)
  788. si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE)
  789. when useWinUnicode:
  790. var c = newWideCString(command)
  791. var res = winlean.createProcessW(nil, c, nil, nil, 0,
  792. NORMAL_PRIORITY_CLASS, nil, nil, si, procInfo)
  793. else:
  794. var res = winlean.createProcessA(nil, command, nil, nil, 0,
  795. NORMAL_PRIORITY_CLASS, nil, nil, si, procInfo)
  796. if res == 0:
  797. raiseOSError(osLastError())
  798. else:
  799. process = procInfo.hProcess
  800. discard closeHandle(procInfo.hThread)
  801. if waitForSingleObject(process, INFINITE) != -1:
  802. discard getExitCodeProcess(process, L)
  803. result = int(L)
  804. else:
  805. result = -1
  806. discard closeHandle(process)
  807. proc select(readfds: var seq[Process], timeout = 500): int =
  808. assert readfds.len <= MAXIMUM_WAIT_OBJECTS
  809. var rfds: WOHandleArray
  810. for i in 0..readfds.len()-1:
  811. rfds[i] = readfds[i].outHandle #fProcessHandle
  812. var ret = waitForMultipleObjects(readfds.len.int32,
  813. addr(rfds), 0'i32, timeout.int32)
  814. case ret
  815. of WAIT_TIMEOUT:
  816. return 0
  817. of WAIT_FAILED:
  818. raiseOSError(osLastError())
  819. else:
  820. var i = ret - WAIT_OBJECT_0
  821. readfds.del(i)
  822. return 1
  823. proc hasData*(p: Process): bool =
  824. var x: int32
  825. if peekNamedPipe(p.outHandle, lpTotalBytesAvail = addr x):
  826. result = x > 0
  827. elif not defined(useNimRtl):
  828. const
  829. readIdx = 0
  830. writeIdx = 1
  831. proc isExitStatus(status: cint): bool =
  832. WIFEXITED(status) or WIFSIGNALED(status)
  833. proc envToCStringArray(t: StringTableRef): cstringArray =
  834. result = cast[cstringArray](alloc0((t.len + 1) * sizeof(cstring)))
  835. var i = 0
  836. for key, val in pairs(t):
  837. var x = key & "=" & val
  838. result[i] = cast[cstring](alloc(x.len+1))
  839. copyMem(result[i], addr(x[0]), x.len+1)
  840. inc(i)
  841. proc envToCStringArray(): cstringArray =
  842. var counter = 0
  843. for key, val in envPairs(): inc counter
  844. result = cast[cstringArray](alloc0((counter + 1) * sizeof(cstring)))
  845. var i = 0
  846. for key, val in envPairs():
  847. var x = key & "=" & val
  848. result[i] = cast[cstring](alloc(x.len+1))
  849. copyMem(result[i], addr(x[0]), x.len+1)
  850. inc(i)
  851. type
  852. StartProcessData = object
  853. sysCommand: string
  854. sysArgs: cstringArray
  855. sysEnv: cstringArray
  856. workingDir: cstring
  857. pStdin, pStdout, pStderr, pErrorPipe: array[0..1, cint]
  858. options: set[ProcessOption]
  859. const useProcessAuxSpawn = declared(posix_spawn) and not defined(useFork) and
  860. not defined(useClone) and not defined(linux)
  861. when useProcessAuxSpawn:
  862. proc startProcessAuxSpawn(data: StartProcessData): Pid {.
  863. tags: [ExecIOEffect, ReadEnvEffect, ReadDirEffect, RootEffect], gcsafe.}
  864. else:
  865. proc startProcessAuxFork(data: StartProcessData): Pid {.
  866. tags: [ExecIOEffect, ReadEnvEffect, ReadDirEffect, RootEffect], gcsafe.}
  867. {.push stacktrace: off, profiler: off.}
  868. proc startProcessAfterFork(data: ptr StartProcessData) {.
  869. tags: [ExecIOEffect, ReadEnvEffect, ReadDirEffect, RootEffect], cdecl, gcsafe.}
  870. {.pop.}
  871. proc startProcess(command: string, workingDir: string = "",
  872. args: openArray[string] = [], env: StringTableRef = nil,
  873. options: set[ProcessOption] = {poStdErrToStdOut}):
  874. owned Process =
  875. var
  876. pStdin, pStdout, pStderr: array[0..1, cint]
  877. new(result)
  878. result.options = options
  879. result.exitFlag = true
  880. if poParentStreams notin options:
  881. if pipe(pStdin) != 0'i32 or pipe(pStdout) != 0'i32 or
  882. pipe(pStderr) != 0'i32:
  883. raiseOSError(osLastError())
  884. var data: StartProcessData
  885. var sysArgsRaw: seq[string]
  886. if poEvalCommand in options:
  887. const useShPath {.strdefine.} =
  888. when not defined(android): "/bin/sh"
  889. else: "/system/bin/sh"
  890. data.sysCommand = useShPath
  891. sysArgsRaw = @[useShPath, "-c", command]
  892. assert args.len == 0, "`args` has to be empty when using poEvalCommand."
  893. else:
  894. data.sysCommand = command
  895. sysArgsRaw = @[command]
  896. for arg in args.items:
  897. sysArgsRaw.add arg
  898. var pid: Pid
  899. var sysArgs = allocCStringArray(sysArgsRaw)
  900. defer: deallocCStringArray(sysArgs)
  901. var sysEnv = if env == nil:
  902. envToCStringArray()
  903. else:
  904. envToCStringArray(env)
  905. defer: deallocCStringArray(sysEnv)
  906. data.sysArgs = sysArgs
  907. data.sysEnv = sysEnv
  908. data.pStdin = pStdin
  909. data.pStdout = pStdout
  910. data.pStderr = pStderr
  911. data.workingDir = workingDir
  912. data.options = options
  913. when useProcessAuxSpawn:
  914. var currentDir = getCurrentDir()
  915. pid = startProcessAuxSpawn(data)
  916. if workingDir.len > 0:
  917. setCurrentDir(currentDir)
  918. else:
  919. pid = startProcessAuxFork(data)
  920. # Parent process. Copy process information.
  921. if poEchoCmd in options:
  922. echo(command, " ", join(args, " "))
  923. result.id = pid
  924. result.exitFlag = false
  925. if poParentStreams in options:
  926. # does not make much sense, but better than nothing:
  927. result.inHandle = 0
  928. result.outHandle = 1
  929. if poStdErrToStdOut in options:
  930. result.errHandle = result.outHandle
  931. else:
  932. result.errHandle = 2
  933. else:
  934. result.inHandle = pStdin[writeIdx]
  935. result.outHandle = pStdout[readIdx]
  936. if poStdErrToStdOut in options:
  937. result.errHandle = result.outHandle
  938. discard close(pStderr[readIdx])
  939. else:
  940. result.errHandle = pStderr[readIdx]
  941. discard close(pStderr[writeIdx])
  942. discard close(pStdin[readIdx])
  943. discard close(pStdout[writeIdx])
  944. when useProcessAuxSpawn:
  945. proc startProcessAuxSpawn(data: StartProcessData): Pid =
  946. var attr: Tposix_spawnattr
  947. var fops: Tposix_spawn_file_actions
  948. template chck(e: untyped) =
  949. if e != 0'i32: raiseOSError(osLastError())
  950. chck posix_spawn_file_actions_init(fops)
  951. chck posix_spawnattr_init(attr)
  952. var mask: Sigset
  953. chck sigemptyset(mask)
  954. chck posix_spawnattr_setsigmask(attr, mask)
  955. if poDaemon in data.options:
  956. chck posix_spawnattr_setpgroup(attr, 0'i32)
  957. var flags = POSIX_SPAWN_USEVFORK or
  958. POSIX_SPAWN_SETSIGMASK
  959. if poDaemon in data.options:
  960. flags = flags or POSIX_SPAWN_SETPGROUP
  961. chck posix_spawnattr_setflags(attr, flags)
  962. if not (poParentStreams in data.options):
  963. chck posix_spawn_file_actions_addclose(fops, data.pStdin[writeIdx])
  964. chck posix_spawn_file_actions_adddup2(fops, data.pStdin[readIdx], readIdx)
  965. chck posix_spawn_file_actions_addclose(fops, data.pStdout[readIdx])
  966. chck posix_spawn_file_actions_adddup2(fops, data.pStdout[writeIdx], writeIdx)
  967. chck posix_spawn_file_actions_addclose(fops, data.pStderr[readIdx])
  968. if poStdErrToStdOut in data.options:
  969. chck posix_spawn_file_actions_adddup2(fops, data.pStdout[writeIdx], 2)
  970. else:
  971. chck posix_spawn_file_actions_adddup2(fops, data.pStderr[writeIdx], 2)
  972. var res: cint
  973. if data.workingDir.len > 0:
  974. setCurrentDir($data.workingDir)
  975. var pid: Pid
  976. if (poUsePath in data.options):
  977. res = posix_spawnp(pid, data.sysCommand.cstring, fops, attr, data.sysArgs, data.sysEnv)
  978. else:
  979. res = posix_spawn(pid, data.sysCommand.cstring, fops, attr, data.sysArgs, data.sysEnv)
  980. discard posix_spawn_file_actions_destroy(fops)
  981. discard posix_spawnattr_destroy(attr)
  982. if res != 0'i32: raiseOSError(OSErrorCode(res), data.sysCommand)
  983. return pid
  984. else:
  985. proc startProcessAuxFork(data: StartProcessData): Pid =
  986. if pipe(data.pErrorPipe) != 0:
  987. raiseOSError(osLastError())
  988. defer:
  989. discard close(data.pErrorPipe[readIdx])
  990. var pid: Pid
  991. var dataCopy = data
  992. when defined(useClone):
  993. const stackSize = 65536
  994. let stackEnd = cast[clong](alloc(stackSize))
  995. let stack = cast[pointer](stackEnd + stackSize)
  996. let fn: pointer = startProcessAfterFork
  997. pid = clone(fn, stack,
  998. cint(CLONE_VM or CLONE_VFORK or SIGCHLD),
  999. pointer(addr dataCopy), nil, nil, nil)
  1000. discard close(data.pErrorPipe[writeIdx])
  1001. dealloc(stack)
  1002. else:
  1003. pid = fork()
  1004. if pid == 0:
  1005. startProcessAfterFork(addr(dataCopy))
  1006. exitnow(1)
  1007. discard close(data.pErrorPipe[writeIdx])
  1008. if pid < 0: raiseOSError(osLastError())
  1009. var error: cint
  1010. let sizeRead = read(data.pErrorPipe[readIdx], addr error, sizeof(error))
  1011. if sizeRead == sizeof(error):
  1012. raiseOSError(osLastError(),
  1013. "Could not find command: '$1'. OS error: $2" %
  1014. [$data.sysCommand, $strerror(error)])
  1015. return pid
  1016. {.push stacktrace: off, profiler: off.}
  1017. proc startProcessFail(data: ptr StartProcessData) =
  1018. var error: cint = errno
  1019. discard write(data.pErrorPipe[writeIdx], addr error, sizeof(error))
  1020. exitnow(1)
  1021. when not defined(uClibc) and (not defined(linux) or defined(android)) and
  1022. not defined(haiku):
  1023. var environ {.importc.}: cstringArray
  1024. proc startProcessAfterFork(data: ptr StartProcessData) =
  1025. # Warning: no GC here!
  1026. # Or anything that touches global structures - all called nim procs
  1027. # must be marked with stackTrace:off. Inspect C code after making changes.
  1028. if not (poParentStreams in data.options):
  1029. discard close(data.pStdin[writeIdx])
  1030. if dup2(data.pStdin[readIdx], readIdx) < 0:
  1031. startProcessFail(data)
  1032. discard close(data.pStdout[readIdx])
  1033. if dup2(data.pStdout[writeIdx], writeIdx) < 0:
  1034. startProcessFail(data)
  1035. discard close(data.pStderr[readIdx])
  1036. if (poStdErrToStdOut in data.options):
  1037. if dup2(data.pStdout[writeIdx], 2) < 0:
  1038. startProcessFail(data)
  1039. else:
  1040. if dup2(data.pStderr[writeIdx], 2) < 0:
  1041. startProcessFail(data)
  1042. if data.workingDir.len > 0:
  1043. if chdir(data.workingDir) < 0:
  1044. startProcessFail(data)
  1045. discard close(data.pErrorPipe[readIdx])
  1046. discard fcntl(data.pErrorPipe[writeIdx], F_SETFD, FD_CLOEXEC)
  1047. if (poUsePath in data.options):
  1048. when defined(uClibc) or defined(linux) or defined(haiku):
  1049. # uClibc environment (OpenWrt included) doesn't have the full execvpe
  1050. let exe = findExe(data.sysCommand)
  1051. discard execve(exe.cstring, data.sysArgs, data.sysEnv)
  1052. else:
  1053. # MacOSX doesn't have execvpe, so we need workaround.
  1054. # On MacOSX we can arrive here only from fork, so this is safe:
  1055. environ = data.sysEnv
  1056. discard execvp(data.sysCommand.cstring, data.sysArgs)
  1057. else:
  1058. discard execve(data.sysCommand.cstring, data.sysArgs, data.sysEnv)
  1059. startProcessFail(data)
  1060. {.pop.}
  1061. proc close(p: Process) =
  1062. if poParentStreams notin p.options:
  1063. if p.inStream != nil:
  1064. close(p.inStream)
  1065. else:
  1066. discard close(p.inHandle)
  1067. if p.outStream != nil:
  1068. close(p.outStream)
  1069. else:
  1070. discard close(p.outHandle)
  1071. if p.errStream != nil:
  1072. close(p.errStream)
  1073. else:
  1074. discard close(p.errHandle)
  1075. proc suspend(p: Process) =
  1076. if kill(p.id, SIGSTOP) != 0'i32: raiseOSError(osLastError())
  1077. proc resume(p: Process) =
  1078. if kill(p.id, SIGCONT) != 0'i32: raiseOSError(osLastError())
  1079. proc running(p: Process): bool =
  1080. if p.exitFlag:
  1081. return false
  1082. else:
  1083. var status: cint = 1
  1084. let ret = waitpid(p.id, status, WNOHANG)
  1085. if ret == int(p.id):
  1086. if isExitStatus(status):
  1087. p.exitFlag = true
  1088. p.exitStatus = status
  1089. return false
  1090. else:
  1091. return true
  1092. elif ret == 0:
  1093. return true # Can't establish status. Assume running.
  1094. else:
  1095. raiseOSError(osLastError())
  1096. proc terminate(p: Process) =
  1097. if kill(p.id, SIGTERM) != 0'i32:
  1098. raiseOSError(osLastError())
  1099. proc kill(p: Process) =
  1100. if kill(p.id, SIGKILL) != 0'i32:
  1101. raiseOSError(osLastError())
  1102. when defined(macosx) or defined(freebsd) or defined(netbsd) or
  1103. defined(openbsd) or defined(dragonfly):
  1104. import kqueue
  1105. proc waitForExit(p: Process, timeout: int = -1): int =
  1106. if p.exitFlag:
  1107. return exitStatusLikeShell(p.exitStatus)
  1108. if timeout == -1:
  1109. var status: cint = 1
  1110. if waitpid(p.id, status, 0) < 0:
  1111. raiseOSError(osLastError())
  1112. p.exitFlag = true
  1113. p.exitStatus = status
  1114. else:
  1115. var kqFD = kqueue()
  1116. if kqFD == -1:
  1117. raiseOSError(osLastError())
  1118. var kevIn = KEvent(ident: p.id.uint, filter: EVFILT_PROC,
  1119. flags: EV_ADD, fflags: NOTE_EXIT)
  1120. var kevOut: KEvent
  1121. var tmspec: Timespec
  1122. if timeout >= 1000:
  1123. tmspec.tv_sec = posix.Time(timeout div 1_000)
  1124. tmspec.tv_nsec = (timeout %% 1_000) * 1_000_000
  1125. else:
  1126. tmspec.tv_sec = posix.Time(0)
  1127. tmspec.tv_nsec = (timeout * 1_000_000)
  1128. try:
  1129. while true:
  1130. var status: cint = 1
  1131. var count = kevent(kqFD, addr(kevIn), 1, addr(kevOut), 1,
  1132. addr(tmspec))
  1133. if count < 0:
  1134. let err = osLastError()
  1135. if err.cint != EINTR:
  1136. raiseOSError(osLastError())
  1137. elif count == 0:
  1138. # timeout expired, so we trying to kill process
  1139. if posix.kill(p.id, SIGKILL) == -1:
  1140. raiseOSError(osLastError())
  1141. if waitpid(p.id, status, 0) < 0:
  1142. raiseOSError(osLastError())
  1143. p.exitFlag = true
  1144. p.exitStatus = status
  1145. break
  1146. else:
  1147. if kevOut.ident == p.id.uint and kevOut.filter == EVFILT_PROC:
  1148. if waitpid(p.id, status, 0) < 0:
  1149. raiseOSError(osLastError())
  1150. p.exitFlag = true
  1151. p.exitStatus = status
  1152. break
  1153. else:
  1154. raiseOSError(osLastError())
  1155. finally:
  1156. discard posix.close(kqFD)
  1157. result = exitStatusLikeShell(p.exitStatus)
  1158. elif defined(haiku):
  1159. const
  1160. B_OBJECT_TYPE_THREAD = 3
  1161. B_EVENT_INVALID = 0x1000
  1162. B_RELATIVE_TIMEOUT = 0x8
  1163. type
  1164. ObjectWaitInfo {.importc: "object_wait_info", header: "OS.h".} = object
  1165. obj {.importc: "object".}: int32
  1166. typ {.importc: "type".}: uint16
  1167. events: uint16
  1168. proc waitForObjects(infos: ptr ObjectWaitInfo, numInfos: cint, flags: uint32,
  1169. timeout: int64): clong
  1170. {.importc: "wait_for_objects_etc", header: "OS.h".}
  1171. proc waitForExit(p: Process, timeout: int = -1): int =
  1172. if p.exitFlag:
  1173. return exitStatusLikeShell(p.exitStatus)
  1174. if timeout == -1:
  1175. var status: cint = 1
  1176. if waitpid(p.id, status, 0) < 0:
  1177. raiseOSError(osLastError())
  1178. p.exitFlag = true
  1179. p.exitStatus = status
  1180. else:
  1181. var info = ObjectWaitInfo(
  1182. obj: p.id, # Haiku's PID is actually the main thread ID.
  1183. typ: B_OBJECT_TYPE_THREAD,
  1184. events: B_EVENT_INVALID # notify when the thread die.
  1185. )
  1186. while true:
  1187. var status: cint = 1
  1188. let count = waitForObjects(addr info, 1, B_RELATIVE_TIMEOUT, timeout)
  1189. if count < 0:
  1190. let err = count.cint
  1191. if err == ETIMEDOUT:
  1192. # timeout expired, so we try to kill the process
  1193. if posix.kill(p.id, SIGKILL) == -1:
  1194. raiseOSError(osLastError())
  1195. if waitpid(p.id, status, 0) < 0:
  1196. raiseOSError(osLastError())
  1197. p.exitFlag = true
  1198. p.exitStatus = status
  1199. break
  1200. elif err != EINTR:
  1201. raiseOSError(err.OSErrorCode)
  1202. elif count > 0:
  1203. if waitpid(p.id, status, 0) < 0:
  1204. raiseOSError(osLastError())
  1205. p.exitFlag = true
  1206. p.exitStatus = status
  1207. break
  1208. else:
  1209. doAssert false, "unreachable!"
  1210. result = exitStatusLikeShell(p.exitStatus)
  1211. else:
  1212. import times
  1213. const
  1214. hasThreadSupport = compileOption("threads") and not defined(nimscript)
  1215. proc waitForExit(p: Process, timeout: int = -1): int =
  1216. template adjustTimeout(t, s, e: Timespec) =
  1217. var diff: int
  1218. var b: Timespec
  1219. b.tv_sec = e.tv_sec
  1220. b.tv_nsec = e.tv_nsec
  1221. e.tv_sec = e.tv_sec - s.tv_sec
  1222. if e.tv_nsec >= s.tv_nsec:
  1223. e.tv_nsec -= s.tv_nsec
  1224. else:
  1225. if e.tv_sec == posix.Time(0):
  1226. raise newException(ValueError, "System time was modified")
  1227. else:
  1228. diff = s.tv_nsec - e.tv_nsec
  1229. e.tv_nsec = 1_000_000_000 - diff
  1230. t.tv_sec = t.tv_sec - e.tv_sec
  1231. if t.tv_nsec >= e.tv_nsec:
  1232. t.tv_nsec -= e.tv_nsec
  1233. else:
  1234. t.tv_sec = t.tv_sec - posix.Time(1)
  1235. diff = e.tv_nsec - t.tv_nsec
  1236. t.tv_nsec = 1_000_000_000 - diff
  1237. s.tv_sec = b.tv_sec
  1238. s.tv_nsec = b.tv_nsec
  1239. if p.exitFlag:
  1240. return exitStatusLikeShell(p.exitStatus)
  1241. if timeout == -1:
  1242. var status: cint = 1
  1243. if waitpid(p.id, status, 0) < 0:
  1244. raiseOSError(osLastError())
  1245. p.exitFlag = true
  1246. p.exitStatus = status
  1247. else:
  1248. var nmask, omask: Sigset
  1249. var sinfo: SigInfo
  1250. var stspec, enspec, tmspec: Timespec
  1251. discard sigemptyset(nmask)
  1252. discard sigemptyset(omask)
  1253. discard sigaddset(nmask, SIGCHLD)
  1254. when hasThreadSupport:
  1255. if pthread_sigmask(SIG_BLOCK, nmask, omask) == -1:
  1256. raiseOSError(osLastError())
  1257. else:
  1258. if sigprocmask(SIG_BLOCK, nmask, omask) == -1:
  1259. raiseOSError(osLastError())
  1260. if timeout >= 1000:
  1261. tmspec.tv_sec = posix.Time(timeout div 1_000)
  1262. tmspec.tv_nsec = (timeout %% 1_000) * 1_000_000
  1263. else:
  1264. tmspec.tv_sec = posix.Time(0)
  1265. tmspec.tv_nsec = (timeout * 1_000_000)
  1266. try:
  1267. if clock_gettime(CLOCK_REALTIME, stspec) == -1:
  1268. raiseOSError(osLastError())
  1269. while true:
  1270. let res = sigtimedwait(nmask, sinfo, tmspec)
  1271. if res == SIGCHLD:
  1272. if sinfo.si_pid == p.id:
  1273. var status: cint = 1
  1274. if waitpid(p.id, status, 0) < 0:
  1275. raiseOSError(osLastError())
  1276. p.exitFlag = true
  1277. p.exitStatus = status
  1278. break
  1279. else:
  1280. # we have SIGCHLD, but not for process we are waiting,
  1281. # so we need to adjust timeout value and continue
  1282. if clock_gettime(CLOCK_REALTIME, enspec) == -1:
  1283. raiseOSError(osLastError())
  1284. adjustTimeout(tmspec, stspec, enspec)
  1285. elif res < 0:
  1286. let err = osLastError()
  1287. if err.cint == EINTR:
  1288. # we have received another signal, so we need to
  1289. # adjust timeout and continue
  1290. if clock_gettime(CLOCK_REALTIME, enspec) == -1:
  1291. raiseOSError(osLastError())
  1292. adjustTimeout(tmspec, stspec, enspec)
  1293. elif err.cint == EAGAIN:
  1294. # timeout expired, so we trying to kill process
  1295. if posix.kill(p.id, SIGKILL) == -1:
  1296. raiseOSError(osLastError())
  1297. var status: cint = 1
  1298. if waitpid(p.id, status, 0) < 0:
  1299. raiseOSError(osLastError())
  1300. p.exitFlag = true
  1301. p.exitStatus = status
  1302. break
  1303. else:
  1304. raiseOSError(err)
  1305. finally:
  1306. when hasThreadSupport:
  1307. if pthread_sigmask(SIG_UNBLOCK, nmask, omask) == -1:
  1308. raiseOSError(osLastError())
  1309. else:
  1310. if sigprocmask(SIG_UNBLOCK, nmask, omask) == -1:
  1311. raiseOSError(osLastError())
  1312. result = exitStatusLikeShell(p.exitStatus)
  1313. proc peekExitCode(p: Process): int =
  1314. var status = cint(0)
  1315. result = -1
  1316. if p.exitFlag:
  1317. return exitStatusLikeShell(p.exitStatus)
  1318. var ret = waitpid(p.id, status, WNOHANG)
  1319. if ret > 0:
  1320. if isExitStatus(status):
  1321. p.exitFlag = true
  1322. p.exitStatus = status
  1323. result = exitStatusLikeShell(status)
  1324. proc createStream(handle: var FileHandle,
  1325. fileMode: FileMode): owned FileStream =
  1326. var f: File
  1327. if not open(f, handle, fileMode): raiseOSError(osLastError())
  1328. return newFileStream(f)
  1329. proc inputStream(p: Process): Stream =
  1330. streamAccess(p)
  1331. if p.inStream == nil:
  1332. p.inStream = createStream(p.inHandle, fmWrite)
  1333. return p.inStream
  1334. proc outputStream(p: Process): Stream =
  1335. streamAccess(p)
  1336. if p.outStream == nil:
  1337. p.outStream = createStream(p.outHandle, fmRead)
  1338. return p.outStream
  1339. proc errorStream(p: Process): Stream =
  1340. streamAccess(p)
  1341. if p.errStream == nil:
  1342. p.errStream = createStream(p.errHandle, fmRead)
  1343. return p.errStream
  1344. proc peekableOutputStream(p: Process): Stream =
  1345. streamAccess(p)
  1346. if p.outStream == nil:
  1347. p.outStream = createStream(p.outHandle, fmRead).newPipeOutStream
  1348. return p.outStream
  1349. proc peekableErrorStream(p: Process): Stream =
  1350. streamAccess(p)
  1351. if p.errStream == nil:
  1352. p.errStream = createStream(p.errHandle, fmRead).newPipeOutStream
  1353. return p.errStream
  1354. proc csystem(cmd: cstring): cint {.nodecl, importc: "system",
  1355. header: "<stdlib.h>".}
  1356. proc execCmd(command: string): int =
  1357. when defined(posix):
  1358. let tmp = csystem(command)
  1359. result = if tmp == -1: tmp else: exitStatusLikeShell(tmp)
  1360. else:
  1361. result = csystem(command)
  1362. proc createFdSet(fd: var TFdSet, s: seq[Process], m: var int) =
  1363. FD_ZERO(fd)
  1364. for i in items(s):
  1365. m = max(m, int(i.outHandle))
  1366. FD_SET(cint(i.outHandle), fd)
  1367. proc pruneProcessSet(s: var seq[Process], fd: var TFdSet) =
  1368. var i = 0
  1369. var L = s.len
  1370. while i < L:
  1371. if FD_ISSET(cint(s[i].outHandle), fd) == 0'i32:
  1372. s[i] = s[L-1]
  1373. dec(L)
  1374. else:
  1375. inc(i)
  1376. setLen(s, L)
  1377. proc select(readfds: var seq[Process], timeout = 500): int =
  1378. var tv: Timeval
  1379. tv.tv_sec = posix.Time(0)
  1380. tv.tv_usec = Suseconds(timeout * 1000)
  1381. var rd: TFdSet
  1382. var m = 0
  1383. createFdSet((rd), readfds, m)
  1384. if timeout != -1:
  1385. result = int(select(cint(m+1), addr(rd), nil, nil, addr(tv)))
  1386. else:
  1387. result = int(select(cint(m+1), addr(rd), nil, nil, nil))
  1388. pruneProcessSet(readfds, (rd))
  1389. proc hasData*(p: Process): bool =
  1390. var rd: TFdSet
  1391. FD_ZERO(rd)
  1392. let m = max(0, int(p.outHandle))
  1393. FD_SET(cint(p.outHandle), rd)
  1394. result = int(select(cint(m+1), addr(rd), nil, nil, nil)) == 1
  1395. proc execCmdEx*(command: string, options: set[ProcessOption] = {
  1396. poStdErrToStdOut, poUsePath}, env: StringTableRef = nil,
  1397. workingDir = "", input = ""): tuple[
  1398. output: string,
  1399. exitCode: int] {.tags:
  1400. [ExecIOEffect, ReadIOEffect, RootEffect], gcsafe.} =
  1401. ## A convenience proc that runs the `command`, and returns its `output` and
  1402. ## `exitCode`. `env` and `workingDir` params behave as for `startProcess`.
  1403. ## If `input.len > 0`, it is passed as stdin.
  1404. ##
  1405. ## Note: this could block if `input.len` is greater than your OS's maximum
  1406. ## pipe buffer size.
  1407. ##
  1408. ## See also:
  1409. ## * `execCmd proc <#execCmd,string>`_
  1410. ## * `startProcess proc
  1411. ## <#startProcess,string,string,openArray[string],StringTableRef,set[ProcessOption]>`_
  1412. ## * `execProcess proc
  1413. ## <#execProcess,string,string,openArray[string],StringTableRef,set[ProcessOption]>`_
  1414. ##
  1415. ## Example:
  1416. ##
  1417. ## .. code-block:: Nim
  1418. ## var result = execCmdEx("nim r --hints:off -", options = {}, input = "echo 3*4")
  1419. ## import std/[strutils, strtabs]
  1420. ## stripLineEnd(result[0]) ## portable way to remove trailing newline, if any
  1421. ## doAssert result == ("12", 0)
  1422. ## doAssert execCmdEx("ls --nonexistent").exitCode != 0
  1423. ## when defined(posix):
  1424. ## assert execCmdEx("echo $FO", env = newStringTable({"FO": "B"})) == ("B\n", 0)
  1425. ## assert execCmdEx("echo $PWD", workingDir = "/") == ("/\n", 0)
  1426. when (NimMajor, NimMinor, NimPatch) < (1, 3, 5):
  1427. doAssert input.len == 0
  1428. doAssert workingDir.len == 0
  1429. doAssert env == nil
  1430. var p = startProcess(command, options = options + {poEvalCommand},
  1431. workingDir = workingDir, env = env)
  1432. var outp = outputStream(p)
  1433. if input.len > 0:
  1434. # There is no way to provide input for the child process
  1435. # anymore. Closing it will create EOF on stdin instead of eternal
  1436. # blocking.
  1437. # Writing in chunks would require a selectors (eg kqueue/epoll) to avoid
  1438. # blocking on io.
  1439. inputStream(p).write(input)
  1440. close inputStream(p)
  1441. # consider `p.lines(keepNewLines=true)` to avoid exit code test
  1442. result = ("", -1)
  1443. var line = newStringOfCap(120)
  1444. while true:
  1445. if outp.readLine(line):
  1446. result[0].add(line)
  1447. result[0].add("\n")
  1448. else:
  1449. result[1] = peekExitCode(p)
  1450. if result[1] != -1: break
  1451. close(p)