I'm trying to understand how to effectively use osproc.startProcess with input and output streams. Using execProcess as an starting point, I've written a simple function which calls the unix cat program, passes strings of interest via an inputStream and reads from stdout using an outputStream.
The inputStream documentation specifically warns: "WARNING: The returned Stream should not be closed manually as it is closed when closing the Process p." However if I don't close the inputStream manually as shown in the code below the thread is blocked and never returns.
Can someone offer some insight into how I'm supposed to pass data to an inputStream w/out closing it manually? Thanks!
import osproc, streams
proc cat(strs: seq[string]): string =
var command = "cat"
var p = startProcess(command, options = {poUsePath})
var inp = inputStream(p)
var outp = outputStream(p)
for str in strs:
inp.write(str)
close(inp) # this line is needed or the thread blocks
var line = ""
while true:
if outp.readLine(line):
result.add(line)
result.add("\n")
elif not running(p): break
close(p)
echo cat(@["hello", "world"])
Sorry, I didn't see the post before.
You're almost there. There's two small things missing in your code.
Note however that with cat at least the output stream will never be "done". So you need some stopping criteria.
import osproc, streams
proc cat(strs: seq[string]): string =
var command = "cat"
var p = startProcess(command, options = {poUsePath})
var inp = inputStream(p)
var outp = outputStream(p)
for str in strs:
# append a new line!
inp.write(str & "\n")
# make sure to flush the stream!
inp.flush()
var line = ""
var happy = 0
while p.running:
if happy == strs.len:
# with `cat` there will always theoretically be data coming from the stream, so
# we have some artificial stopping criterium (maybe just Ctrl-C)
break
elif outp.readLine(line):
result.add(line & "\n")
inc happy
close(p)
echo cat(@["hello", "world"])
I tried the above, but it did not help me. I had to close both stdin and stderr before trying to read stdout for it not to hang anymore.
See: https://github.com/nim-lang/Nim/issues/9953#issuecomment-1536157592