osproc.nim 56 KB

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