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. 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, TimeEffect].} =
  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. ## ```Nim
  427. ## const opts = {poUsePath, poDaemon, poStdErrToStdOut}
  428. ## var ps: seq[Process]
  429. ## for prog in ["a", "b"]: # run 2 progs in parallel
  430. ## ps.add startProcess("nim", "", ["r", prog], nil, opts)
  431. ## for p in ps:
  432. ## var i = 0
  433. ## for line in p.lines:
  434. ## echo line
  435. ## i.inc
  436. ## if i > 100: break
  437. ## p.close
  438. ## ```
  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, TimeEffect].} =
  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. ## ```Nim
  456. ## const opts = {poUsePath, poDaemon, poStdErrToStdOut}
  457. ## var ps: seq[Process]
  458. ## for prog in ["a", "b"]: # run 2 progs in parallel
  459. ## ps.add startProcess("nim", "", ["r", prog], nil, opts)
  460. ## for p in ps:
  461. ## let (lines, exCode) = p.readLines
  462. ## if exCode != 0:
  463. ## for line in lines: echo line
  464. ## p.close
  465. ## ```
  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. case lastError.int
  678. of errInvalidParameter, errFileNotFound:
  679. raiseOSError(lastError,
  680. "Requested command not found: '" & command & "'. OS error:")
  681. else:
  682. raiseOSError(lastError, command)
  683. result.fProcessHandle = procInfo.hProcess
  684. result.fThreadHandle = procInfo.hThread
  685. result.id = procInfo.dwProcessId
  686. result.exitFlag = false
  687. proc closeThreadAndProcessHandle(p: Process) =
  688. if p.fThreadHandle != 0:
  689. closeHandleCheck(p.fThreadHandle)
  690. p.fThreadHandle = 0
  691. if p.fProcessHandle != 0:
  692. closeHandleCheck(p.fProcessHandle)
  693. p.fProcessHandle = 0
  694. proc close(p: Process) =
  695. if poParentStreams notin p.options:
  696. if p.inStream == nil:
  697. p.inHandle.fileClose()
  698. else:
  699. # p.inHandle can be already closed via inputStream.
  700. p.inStream.close
  701. # You may NOT close outputStream and errorStream.
  702. assert p.outStream == nil or FileHandleStream(p.outStream).handle != INVALID_HANDLE_VALUE
  703. assert p.errStream == nil or FileHandleStream(p.errStream).handle != INVALID_HANDLE_VALUE
  704. if p.outHandle != p.errHandle:
  705. p.errHandle.fileClose()
  706. p.outHandle.fileClose()
  707. p.closeThreadAndProcessHandle()
  708. proc suspend(p: Process) =
  709. discard suspendThread(p.fThreadHandle)
  710. proc resume(p: Process) =
  711. discard resumeThread(p.fThreadHandle)
  712. proc running(p: Process): bool =
  713. if p.exitFlag:
  714. return false
  715. else:
  716. var x = waitForSingleObject(p.fProcessHandle, 0)
  717. return x == WAIT_TIMEOUT
  718. proc terminate(p: Process) =
  719. if running(p):
  720. discard terminateProcess(p.fProcessHandle, 0)
  721. proc kill(p: Process) =
  722. terminate(p)
  723. proc waitForExit(p: Process, timeout: int = -1): int =
  724. if p.exitFlag:
  725. return p.exitStatus
  726. let res = waitForSingleObject(p.fProcessHandle, timeout.int32)
  727. if res == WAIT_TIMEOUT:
  728. terminate(p)
  729. var status: int32
  730. discard getExitCodeProcess(p.fProcessHandle, status)
  731. if status != STILL_ACTIVE:
  732. p.exitFlag = true
  733. p.exitStatus = status
  734. p.closeThreadAndProcessHandle()
  735. result = status
  736. else:
  737. result = -1
  738. proc peekExitCode(p: Process): int =
  739. if p.exitFlag:
  740. return p.exitStatus
  741. result = -1
  742. var b = waitForSingleObject(p.fProcessHandle, 0) == WAIT_TIMEOUT
  743. if not b:
  744. var status: int32
  745. discard getExitCodeProcess(p.fProcessHandle, status)
  746. p.exitFlag = true
  747. p.exitStatus = status
  748. p.closeThreadAndProcessHandle()
  749. result = status
  750. proc inputStream(p: Process): Stream =
  751. streamAccess(p)
  752. if p.inStream == nil:
  753. p.inStream = newFileHandleStream(p.inHandle)
  754. result = p.inStream
  755. proc outputStream(p: Process): Stream =
  756. streamAccess(p)
  757. if p.outStream == nil:
  758. p.outStream = newFileHandleStream(p.outHandle)
  759. result = p.outStream
  760. proc errorStream(p: Process): Stream =
  761. streamAccess(p)
  762. if p.errStream == nil:
  763. p.errStream = newFileHandleStream(p.errHandle)
  764. result = p.errStream
  765. proc peekableOutputStream(p: Process): Stream =
  766. streamAccess(p)
  767. if p.outStream == nil:
  768. p.outStream = newFileHandleStream(p.outHandle).newPipeOutStream
  769. result = p.outStream
  770. proc peekableErrorStream(p: Process): Stream =
  771. streamAccess(p)
  772. if p.errStream == nil:
  773. p.errStream = newFileHandleStream(p.errHandle).newPipeOutStream
  774. result = p.errStream
  775. proc execCmd(command: string): int =
  776. var
  777. si: STARTUPINFO
  778. procInfo: PROCESS_INFORMATION
  779. process: Handle
  780. L: int32
  781. si.cb = sizeof(si).cint
  782. si.hStdError = getStdHandle(STD_ERROR_HANDLE)
  783. si.hStdInput = getStdHandle(STD_INPUT_HANDLE)
  784. si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE)
  785. var c = newWideCString(command)
  786. var res = winlean.createProcessW(nil, c, nil, nil, 0,
  787. NORMAL_PRIORITY_CLASS, nil, nil, si, procInfo)
  788. if res == 0:
  789. raiseOSError(osLastError())
  790. else:
  791. process = procInfo.hProcess
  792. discard closeHandle(procInfo.hThread)
  793. if waitForSingleObject(process, INFINITE) != -1:
  794. discard getExitCodeProcess(process, L)
  795. result = int(L)
  796. else:
  797. result = -1
  798. discard closeHandle(process)
  799. proc select(readfds: var seq[Process], timeout = 500): int =
  800. assert readfds.len <= MAXIMUM_WAIT_OBJECTS
  801. var rfds: WOHandleArray
  802. for i in 0..readfds.len()-1:
  803. rfds[i] = readfds[i].outHandle #fProcessHandle
  804. var ret = waitForMultipleObjects(readfds.len.int32,
  805. addr(rfds), 0'i32, timeout.int32)
  806. case ret
  807. of WAIT_TIMEOUT:
  808. return 0
  809. of WAIT_FAILED:
  810. raiseOSError(osLastError())
  811. else:
  812. var i = ret - WAIT_OBJECT_0
  813. readfds.del(i)
  814. return 1
  815. proc hasData*(p: Process): bool =
  816. var x: int32
  817. if peekNamedPipe(p.outHandle, lpTotalBytesAvail = addr x):
  818. result = x > 0
  819. elif not defined(useNimRtl):
  820. const
  821. readIdx = 0
  822. writeIdx = 1
  823. proc isExitStatus(status: cint): bool =
  824. WIFEXITED(status) or WIFSIGNALED(status)
  825. proc envToCStringArray(t: StringTableRef): cstringArray =
  826. result = cast[cstringArray](alloc0((t.len + 1) * sizeof(cstring)))
  827. var i = 0
  828. for key, val in pairs(t):
  829. var x = key & "=" & val
  830. result[i] = cast[cstring](alloc(x.len+1))
  831. copyMem(result[i], addr(x[0]), x.len+1)
  832. inc(i)
  833. proc envToCStringArray(): cstringArray =
  834. var counter = 0
  835. for key, val in envPairs(): inc counter
  836. result = cast[cstringArray](alloc0((counter + 1) * sizeof(cstring)))
  837. var i = 0
  838. for key, val in envPairs():
  839. var x = key & "=" & val
  840. result[i] = cast[cstring](alloc(x.len+1))
  841. copyMem(result[i], addr(x[0]), x.len+1)
  842. inc(i)
  843. type
  844. StartProcessData = object
  845. sysCommand: string
  846. sysArgs: cstringArray
  847. sysEnv: cstringArray
  848. workingDir: cstring
  849. pStdin, pStdout, pStderr, pErrorPipe: array[0..1, cint]
  850. options: set[ProcessOption]
  851. const useProcessAuxSpawn = declared(posix_spawn) and not defined(useFork) and
  852. not defined(useClone) and not defined(linux)
  853. when useProcessAuxSpawn:
  854. proc startProcessAuxSpawn(data: StartProcessData): Pid {.
  855. raises: [OSError], tags: [ExecIOEffect, ReadEnvEffect, ReadDirEffect, RootEffect], gcsafe.}
  856. else:
  857. proc startProcessAuxFork(data: StartProcessData): Pid {.
  858. raises: [OSError], tags: [ExecIOEffect, ReadEnvEffect, ReadDirEffect, RootEffect], gcsafe.}
  859. {.push stacktrace: off, profiler: off.}
  860. proc startProcessAfterFork(data: ptr StartProcessData) {.
  861. raises: [OSError], tags: [ExecIOEffect, ReadEnvEffect, ReadDirEffect, RootEffect], cdecl, gcsafe.}
  862. {.pop.}
  863. proc startProcess(command: string, workingDir: string = "",
  864. args: openArray[string] = [], env: StringTableRef = nil,
  865. options: set[ProcessOption] = {poStdErrToStdOut}):
  866. owned Process =
  867. var
  868. pStdin, pStdout, pStderr: array[0..1, cint]
  869. new(result)
  870. result.options = options
  871. result.exitFlag = true
  872. if poParentStreams notin options:
  873. if pipe(pStdin) != 0'i32 or pipe(pStdout) != 0'i32 or
  874. pipe(pStderr) != 0'i32:
  875. raiseOSError(osLastError())
  876. var data: StartProcessData
  877. var sysArgsRaw: seq[string]
  878. if poEvalCommand in options:
  879. const useShPath {.strdefine.} =
  880. when not defined(android): "/bin/sh"
  881. else: "/system/bin/sh"
  882. data.sysCommand = useShPath
  883. sysArgsRaw = @[useShPath, "-c", command]
  884. assert args.len == 0, "`args` has to be empty when using poEvalCommand."
  885. else:
  886. data.sysCommand = command
  887. sysArgsRaw = @[command]
  888. for arg in args.items:
  889. sysArgsRaw.add arg
  890. var pid: Pid
  891. var sysArgs = allocCStringArray(sysArgsRaw)
  892. defer: deallocCStringArray(sysArgs)
  893. var sysEnv = if env == nil:
  894. envToCStringArray()
  895. else:
  896. envToCStringArray(env)
  897. defer: deallocCStringArray(sysEnv)
  898. data.sysArgs = sysArgs
  899. data.sysEnv = sysEnv
  900. data.pStdin = pStdin
  901. data.pStdout = pStdout
  902. data.pStderr = pStderr
  903. data.workingDir = workingDir
  904. data.options = options
  905. when useProcessAuxSpawn:
  906. var currentDir = getCurrentDir()
  907. pid = startProcessAuxSpawn(data)
  908. if workingDir.len > 0:
  909. setCurrentDir(currentDir)
  910. else:
  911. pid = startProcessAuxFork(data)
  912. # Parent process. Copy process information.
  913. if poEchoCmd in options:
  914. echo(command, " ", join(args, " "))
  915. result.id = pid
  916. result.exitFlag = false
  917. if poParentStreams in options:
  918. # does not make much sense, but better than nothing:
  919. result.inHandle = 0
  920. result.outHandle = 1
  921. if poStdErrToStdOut in options:
  922. result.errHandle = result.outHandle
  923. else:
  924. result.errHandle = 2
  925. else:
  926. result.inHandle = pStdin[writeIdx]
  927. result.outHandle = pStdout[readIdx]
  928. if poStdErrToStdOut in options:
  929. result.errHandle = result.outHandle
  930. discard close(pStderr[readIdx])
  931. else:
  932. result.errHandle = pStderr[readIdx]
  933. discard close(pStderr[writeIdx])
  934. discard close(pStdin[readIdx])
  935. discard close(pStdout[writeIdx])
  936. when useProcessAuxSpawn:
  937. proc startProcessAuxSpawn(data: StartProcessData): Pid =
  938. var attr: Tposix_spawnattr
  939. var fops: Tposix_spawn_file_actions
  940. template chck(e: untyped) =
  941. if e != 0'i32: raiseOSError(osLastError())
  942. chck posix_spawn_file_actions_init(fops)
  943. chck posix_spawnattr_init(attr)
  944. var mask: Sigset
  945. chck sigemptyset(mask)
  946. chck posix_spawnattr_setsigmask(attr, mask)
  947. when not defined(nuttx):
  948. if poDaemon in data.options:
  949. chck posix_spawnattr_setpgroup(attr, 0'i32)
  950. var flags = POSIX_SPAWN_USEVFORK or
  951. POSIX_SPAWN_SETSIGMASK
  952. when not defined(nuttx):
  953. if poDaemon in data.options:
  954. flags = flags or POSIX_SPAWN_SETPGROUP
  955. chck posix_spawnattr_setflags(attr, flags)
  956. if not (poParentStreams in data.options):
  957. chck posix_spawn_file_actions_addclose(fops, data.pStdin[writeIdx])
  958. chck posix_spawn_file_actions_adddup2(fops, data.pStdin[readIdx], readIdx)
  959. chck posix_spawn_file_actions_addclose(fops, data.pStdout[readIdx])
  960. chck posix_spawn_file_actions_adddup2(fops, data.pStdout[writeIdx], writeIdx)
  961. chck posix_spawn_file_actions_addclose(fops, data.pStderr[readIdx])
  962. if poStdErrToStdOut in data.options:
  963. chck posix_spawn_file_actions_adddup2(fops, data.pStdout[writeIdx], 2)
  964. else:
  965. chck posix_spawn_file_actions_adddup2(fops, data.pStderr[writeIdx], 2)
  966. var res: cint
  967. if data.workingDir.len > 0:
  968. setCurrentDir($data.workingDir)
  969. var pid: Pid
  970. if (poUsePath in data.options):
  971. res = posix_spawnp(pid, data.sysCommand.cstring, fops, attr, data.sysArgs, data.sysEnv)
  972. else:
  973. res = posix_spawn(pid, data.sysCommand.cstring, fops, attr, data.sysArgs, data.sysEnv)
  974. discard posix_spawn_file_actions_destroy(fops)
  975. discard posix_spawnattr_destroy(attr)
  976. if res != 0'i32: raiseOSError(OSErrorCode(res), data.sysCommand)
  977. return pid
  978. else:
  979. proc startProcessAuxFork(data: StartProcessData): Pid =
  980. if pipe(data.pErrorPipe) != 0:
  981. raiseOSError(osLastError())
  982. defer:
  983. discard close(data.pErrorPipe[readIdx])
  984. var pid: Pid
  985. var dataCopy = data
  986. when defined(useClone):
  987. const stackSize = 65536
  988. let stackEnd = cast[clong](alloc(stackSize))
  989. let stack = cast[pointer](stackEnd + stackSize)
  990. let fn: pointer = startProcessAfterFork
  991. pid = clone(fn, stack,
  992. cint(CLONE_VM or CLONE_VFORK or SIGCHLD),
  993. pointer(addr dataCopy), nil, nil, nil)
  994. discard close(data.pErrorPipe[writeIdx])
  995. dealloc(stack)
  996. else:
  997. pid = fork()
  998. if pid == 0:
  999. startProcessAfterFork(addr(dataCopy))
  1000. exitnow(1)
  1001. discard close(data.pErrorPipe[writeIdx])
  1002. if pid < 0: raiseOSError(osLastError())
  1003. var error: cint
  1004. let sizeRead = read(data.pErrorPipe[readIdx], addr error, sizeof(error))
  1005. if sizeRead == sizeof(error):
  1006. raiseOSError(OSErrorCode(error),
  1007. "Could not find command: '" & $data.sysCommand & "'. OS error: " & $strerror(error))
  1008. return pid
  1009. {.push stacktrace: off, profiler: off.}
  1010. proc startProcessFail(data: ptr StartProcessData, 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. var exe: string
  1043. try:
  1044. exe = findExe(data.sysCommand)
  1045. except OSError as e:
  1046. startProcessFail(data, e.errorCode)
  1047. discard execve(exe.cstring, data.sysArgs, data.sysEnv)
  1048. else:
  1049. # MacOSX doesn't have execvpe, so we need workaround.
  1050. # On MacOSX we can arrive here only from fork, so this is safe:
  1051. environ = data.sysEnv
  1052. discard execvp(data.sysCommand.cstring, data.sysArgs)
  1053. else:
  1054. discard execve(data.sysCommand.cstring, data.sysArgs, data.sysEnv)
  1055. startProcessFail(data)
  1056. {.pop.}
  1057. proc close(p: Process) =
  1058. if poParentStreams notin p.options:
  1059. if p.inStream != nil:
  1060. close(p.inStream)
  1061. else:
  1062. discard close(p.inHandle)
  1063. if p.outStream != nil:
  1064. close(p.outStream)
  1065. else:
  1066. discard close(p.outHandle)
  1067. if p.errStream != nil:
  1068. close(p.errStream)
  1069. else:
  1070. discard close(p.errHandle)
  1071. proc suspend(p: Process) =
  1072. if kill(p.id, SIGSTOP) != 0'i32: raiseOSError(osLastError())
  1073. proc resume(p: Process) =
  1074. if kill(p.id, SIGCONT) != 0'i32: raiseOSError(osLastError())
  1075. proc running(p: Process): bool =
  1076. if p.exitFlag:
  1077. return false
  1078. else:
  1079. var status: cint = 1
  1080. let ret = waitpid(p.id, status, WNOHANG)
  1081. if ret == int(p.id):
  1082. if isExitStatus(status):
  1083. p.exitFlag = true
  1084. p.exitStatus = status
  1085. return false
  1086. else:
  1087. return true
  1088. elif ret == 0:
  1089. return true # Can't establish status. Assume running.
  1090. else:
  1091. raiseOSError(osLastError())
  1092. proc terminate(p: Process) =
  1093. if kill(p.id, SIGTERM) != 0'i32:
  1094. raiseOSError(osLastError())
  1095. proc kill(p: Process) =
  1096. if kill(p.id, SIGKILL) != 0'i32:
  1097. raiseOSError(osLastError())
  1098. when defined(macosx) or defined(freebsd) or defined(netbsd) or
  1099. defined(openbsd) or defined(dragonfly):
  1100. import std/kqueue
  1101. proc waitForExit(p: Process, timeout: int = -1): int =
  1102. if p.exitFlag:
  1103. return exitStatusLikeShell(p.exitStatus)
  1104. if timeout == -1:
  1105. var status: cint = 1
  1106. if waitpid(p.id, status, 0) < 0:
  1107. raiseOSError(osLastError())
  1108. p.exitFlag = true
  1109. p.exitStatus = status
  1110. else:
  1111. var kqFD = kqueue()
  1112. if kqFD == -1:
  1113. raiseOSError(osLastError())
  1114. var kevIn = KEvent(ident: p.id.uint, filter: EVFILT_PROC,
  1115. flags: EV_ADD, fflags: NOTE_EXIT)
  1116. var kevOut: KEvent
  1117. var tmspec: Timespec
  1118. if timeout >= 1000:
  1119. tmspec.tv_sec = posix.Time(timeout div 1_000)
  1120. tmspec.tv_nsec = (timeout %% 1_000) * 1_000_000
  1121. else:
  1122. tmspec.tv_sec = posix.Time(0)
  1123. tmspec.tv_nsec = (timeout * 1_000_000)
  1124. try:
  1125. while true:
  1126. var status: cint = 1
  1127. var count = kevent(kqFD, addr(kevIn), 1, addr(kevOut), 1,
  1128. addr(tmspec))
  1129. if count < 0:
  1130. let err = osLastError()
  1131. if err.cint != EINTR:
  1132. raiseOSError(osLastError())
  1133. elif count == 0:
  1134. # timeout expired, so we trying to kill process
  1135. if posix.kill(p.id, SIGKILL) == -1:
  1136. raiseOSError(osLastError())
  1137. if waitpid(p.id, status, 0) < 0:
  1138. raiseOSError(osLastError())
  1139. p.exitFlag = true
  1140. p.exitStatus = status
  1141. break
  1142. else:
  1143. if kevOut.ident == p.id.uint and kevOut.filter == EVFILT_PROC:
  1144. if waitpid(p.id, status, 0) < 0:
  1145. raiseOSError(osLastError())
  1146. p.exitFlag = true
  1147. p.exitStatus = status
  1148. break
  1149. else:
  1150. raiseOSError(osLastError())
  1151. finally:
  1152. discard posix.close(kqFD)
  1153. result = exitStatusLikeShell(p.exitStatus)
  1154. elif defined(haiku):
  1155. const
  1156. B_OBJECT_TYPE_THREAD = 3
  1157. B_EVENT_INVALID = 0x1000
  1158. B_RELATIVE_TIMEOUT = 0x8
  1159. type
  1160. ObjectWaitInfo {.importc: "object_wait_info", header: "OS.h".} = object
  1161. obj {.importc: "object".}: int32
  1162. typ {.importc: "type".}: uint16
  1163. events: uint16
  1164. proc waitForObjects(infos: ptr ObjectWaitInfo, numInfos: cint, flags: uint32,
  1165. timeout: int64): clong
  1166. {.importc: "wait_for_objects_etc", header: "OS.h".}
  1167. proc waitForExit(p: Process, timeout: int = -1): int =
  1168. if p.exitFlag:
  1169. return exitStatusLikeShell(p.exitStatus)
  1170. if timeout == -1:
  1171. var status: cint = 1
  1172. if waitpid(p.id, status, 0) < 0:
  1173. raiseOSError(osLastError())
  1174. p.exitFlag = true
  1175. p.exitStatus = status
  1176. else:
  1177. var info = ObjectWaitInfo(
  1178. obj: p.id, # Haiku's PID is actually the main thread ID.
  1179. typ: B_OBJECT_TYPE_THREAD,
  1180. events: B_EVENT_INVALID # notify when the thread die.
  1181. )
  1182. while true:
  1183. var status: cint = 1
  1184. let count = waitForObjects(addr info, 1, B_RELATIVE_TIMEOUT, timeout)
  1185. if count < 0:
  1186. let err = count.cint
  1187. if err == ETIMEDOUT:
  1188. # timeout expired, so we try to kill the process
  1189. if posix.kill(p.id, SIGKILL) == -1:
  1190. raiseOSError(osLastError())
  1191. if waitpid(p.id, status, 0) < 0:
  1192. raiseOSError(osLastError())
  1193. p.exitFlag = true
  1194. p.exitStatus = status
  1195. break
  1196. elif err != EINTR:
  1197. raiseOSError(err.OSErrorCode)
  1198. elif count > 0:
  1199. if waitpid(p.id, status, 0) < 0:
  1200. raiseOSError(osLastError())
  1201. p.exitFlag = true
  1202. p.exitStatus = status
  1203. break
  1204. else:
  1205. raiseAssert "unreachable!"
  1206. result = exitStatusLikeShell(p.exitStatus)
  1207. else:
  1208. import std/times except getTime
  1209. import std/monotimes
  1210. proc waitForExit(p: Process, timeout: int = -1): int =
  1211. if p.exitFlag:
  1212. return exitStatusLikeShell(p.exitStatus)
  1213. if timeout < 0:
  1214. # Backwards compatibility with previous verison to
  1215. # handle cases where timeout == -1, but extend
  1216. # to handle cases where timeout < 0
  1217. var status: cint
  1218. if waitpid(p.id, status, 0) < 0:
  1219. raiseOSError(osLastError())
  1220. p.exitFlag = true
  1221. p.exitStatus = status
  1222. else:
  1223. # Max 50ms delay
  1224. const maxWait = initDuration(milliseconds = 50)
  1225. let wait = initDuration(milliseconds = timeout)
  1226. let deadline = getMonoTime() + wait
  1227. # starting 50μs delay
  1228. var delay = initDuration(microseconds = 50)
  1229. while true:
  1230. var status: cint
  1231. let pid = waitpid(p.id, status, WNOHANG)
  1232. if p.id == pid :
  1233. p.exitFlag = true
  1234. p.exitStatus = status
  1235. break
  1236. elif pid.int == -1:
  1237. raiseOsError(osLastError())
  1238. else:
  1239. # Continue waiting if needed
  1240. if getMonoTime() >= deadline:
  1241. # Previous version of `waitForExit`
  1242. # foricibly killed the process.
  1243. # We keep this so we don't break programs
  1244. # that depend on this behavior
  1245. if posix.kill(p.id, SIGKILL) < 0:
  1246. raiseOSError(osLastError())
  1247. else:
  1248. const max = 1_000_000_000
  1249. let
  1250. newWait = getMonoTime() + delay
  1251. ticks = newWait.ticks()
  1252. ns = ticks mod max
  1253. secs = ticks div max
  1254. var
  1255. waitSpec: TimeSpec
  1256. unused: Timespec
  1257. waitSpec.tv_sec = posix.Time(secs)
  1258. waitSpec.tv_nsec = clong ns
  1259. discard posix.clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, waitSpec, unused)
  1260. let remaining = deadline - getMonoTime()
  1261. delay = min([delay * 2, remaining, maxWait])
  1262. result = exitStatusLikeShell(p.exitStatus)
  1263. proc peekExitCode(p: Process): int =
  1264. var status = cint(0)
  1265. result = -1
  1266. if p.exitFlag:
  1267. return exitStatusLikeShell(p.exitStatus)
  1268. var ret = waitpid(p.id, status, WNOHANG)
  1269. if ret > 0:
  1270. if isExitStatus(status):
  1271. p.exitFlag = true
  1272. p.exitStatus = status
  1273. result = exitStatusLikeShell(status)
  1274. proc createStream(handle: var FileHandle,
  1275. fileMode: FileMode): owned FileStream =
  1276. var f: File
  1277. if not open(f, handle, fileMode): raiseOSError(osLastError())
  1278. return newFileStream(f)
  1279. proc inputStream(p: Process): Stream =
  1280. streamAccess(p)
  1281. if p.inStream == nil:
  1282. p.inStream = createStream(p.inHandle, fmWrite)
  1283. return p.inStream
  1284. proc outputStream(p: Process): Stream =
  1285. streamAccess(p)
  1286. if p.outStream == nil:
  1287. p.outStream = createStream(p.outHandle, fmRead)
  1288. return p.outStream
  1289. proc errorStream(p: Process): Stream =
  1290. streamAccess(p)
  1291. if p.errStream == nil:
  1292. p.errStream = createStream(p.errHandle, fmRead)
  1293. return p.errStream
  1294. proc peekableOutputStream(p: Process): Stream =
  1295. streamAccess(p)
  1296. if p.outStream == nil:
  1297. p.outStream = createStream(p.outHandle, fmRead).newPipeOutStream
  1298. return p.outStream
  1299. proc peekableErrorStream(p: Process): Stream =
  1300. streamAccess(p)
  1301. if p.errStream == nil:
  1302. p.errStream = createStream(p.errHandle, fmRead).newPipeOutStream
  1303. return p.errStream
  1304. proc csystem(cmd: cstring): cint {.nodecl, importc: "system",
  1305. header: "<stdlib.h>".}
  1306. proc execCmd(command: string): int =
  1307. when defined(posix):
  1308. let tmp = csystem(command)
  1309. result = if tmp == -1: tmp else: exitStatusLikeShell(tmp)
  1310. else:
  1311. result = csystem(command)
  1312. proc createFdSet(fd: var TFdSet, s: seq[Process], m: var int) =
  1313. FD_ZERO(fd)
  1314. for i in items(s):
  1315. m = max(m, int(i.outHandle))
  1316. FD_SET(cint(i.outHandle), fd)
  1317. proc pruneProcessSet(s: var seq[Process], fd: var TFdSet) =
  1318. var i = 0
  1319. var L = s.len
  1320. while i < L:
  1321. if FD_ISSET(cint(s[i].outHandle), fd) == 0'i32:
  1322. s[i] = s[L-1]
  1323. dec(L)
  1324. else:
  1325. inc(i)
  1326. setLen(s, L)
  1327. proc select(readfds: var seq[Process], timeout = 500): int =
  1328. var tv: Timeval
  1329. tv.tv_sec = posix.Time(0)
  1330. tv.tv_usec = Suseconds(timeout * 1000)
  1331. var rd: TFdSet
  1332. var m = 0
  1333. createFdSet((rd), readfds, m)
  1334. if timeout != -1:
  1335. result = int(select(cint(m+1), addr(rd), nil, nil, addr(tv)))
  1336. else:
  1337. result = int(select(cint(m+1), addr(rd), nil, nil, nil))
  1338. pruneProcessSet(readfds, (rd))
  1339. proc hasData*(p: Process): bool =
  1340. var rd: TFdSet
  1341. FD_ZERO(rd)
  1342. let m = max(0, int(p.outHandle))
  1343. FD_SET(cint(p.outHandle), rd)
  1344. result = int(select(cint(m+1), addr(rd), nil, nil, nil)) == 1
  1345. proc execCmdEx*(command: string, options: set[ProcessOption] = {
  1346. poStdErrToStdOut, poUsePath}, env: StringTableRef = nil,
  1347. workingDir = "", input = ""): tuple[
  1348. output: string,
  1349. exitCode: int] {.raises: [OSError, IOError], tags:
  1350. [ExecIOEffect, ReadIOEffect, RootEffect], gcsafe.} =
  1351. ## A convenience proc that runs the `command`, and returns its `output` and
  1352. ## `exitCode`. `env` and `workingDir` params behave as for `startProcess`.
  1353. ## If `input.len > 0`, it is passed as stdin.
  1354. ##
  1355. ## Note: this could block if `input.len` is greater than your OS's maximum
  1356. ## pipe buffer size.
  1357. ##
  1358. ## See also:
  1359. ## * `execCmd proc <#execCmd,string>`_
  1360. ## * `startProcess proc
  1361. ## <#startProcess,string,string,openArray[string],StringTableRef,set[ProcessOption]>`_
  1362. ## * `execProcess proc
  1363. ## <#execProcess,string,string,openArray[string],StringTableRef,set[ProcessOption]>`_
  1364. ##
  1365. ## Example:
  1366. ## ```Nim
  1367. ## var result = execCmdEx("nim r --hints:off -", options = {}, input = "echo 3*4")
  1368. ## import std/[strutils, strtabs]
  1369. ## stripLineEnd(result[0]) ## portable way to remove trailing newline, if any
  1370. ## doAssert result == ("12", 0)
  1371. ## doAssert execCmdEx("ls --nonexistent").exitCode != 0
  1372. ## when defined(posix):
  1373. ## assert execCmdEx("echo $FO", env = newStringTable({"FO": "B"})) == ("B\n", 0)
  1374. ## assert execCmdEx("echo $PWD", workingDir = "/") == ("/\n", 0)
  1375. ## ```
  1376. when (NimMajor, NimMinor, NimPatch) < (1, 3, 5):
  1377. doAssert input.len == 0
  1378. doAssert workingDir.len == 0
  1379. doAssert env == nil
  1380. var p = startProcess(command, options = options + {poEvalCommand},
  1381. workingDir = workingDir, env = env)
  1382. var outp = outputStream(p)
  1383. if input.len > 0:
  1384. # There is no way to provide input for the child process
  1385. # anymore. Closing it will create EOF on stdin instead of eternal
  1386. # blocking.
  1387. # Writing in chunks would require a selectors (eg kqueue/epoll) to avoid
  1388. # blocking on io.
  1389. inputStream(p).write(input)
  1390. close inputStream(p)
  1391. # consider `p.lines(keepNewLines=true)` to avoid exit code test
  1392. result = ("", -1)
  1393. var line = newStringOfCap(120)
  1394. while true:
  1395. if outp.readLine(line):
  1396. result[0].add(line)
  1397. result[0].add("\n")
  1398. else:
  1399. result[1] = peekExitCode(p)
  1400. if result[1] != -1: break
  1401. close(p)