osproc.nim 55 KB

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