osproc.nim 54 KB

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