osproc.nim 56 KB

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