Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help with asyncproc simultaneous stdout & stderr? #24

Open
akavel opened this issue Feb 13, 2020 · 1 comment
Open

Help with asyncproc simultaneous stdout & stderr? #24

akavel opened this issue Feb 13, 2020 · 1 comment

Comments

@akavel
Copy link

akavel commented Feb 13, 2020

Hi, I'm trying to write an app that could start a subprocess, and react to its stdout or stderr, depending on what shows up. I was given some initial advice on Nim forum, and I tried to build something based on it, but I think I must be doing something wrong, as I'm not getting results I was expecting :( I have files like below:

q_async.nim

import asynctools/[asyncproc, asyncpipe]
import asyncfutures
import asyncdispatch

var p = startProcess("q_outerr", options = {})
var pout = p.outputHandle
var perr = p.errorHandle

proc next() {.async.} =
  var bufo = newString(1)
  var fo = pout.readInto(bufo[0].addr, bufo.len)
  var bufe = newString(1)
  var fe = perr.readInto(bufe[0].addr, bufe.len)
  var fx = p.waitForExit()
  while true:
    await fe or fo or fx
    if fo.finished:
      if fo.read > 0:
        echo "O ", fo.read(), " ", bufo.substr(0, fo.read()-1)
      fo = pout.readInto(bufo[0].addr, bufo.len)
    if fe.finished:
      if fe.read > 0:
        echo "E ", fe.read(), " ", bufe.substr(0, fe.read()-1)
      fe = perr.readInto(bufe[0].addr, bufe.len)
    if fx.finished:
      echo "X ", fx.read()
      return
    if fo.finished and fe.finished and fo.read==0 and fe.read==0:
      return

waitFor next()

q_outerr.nim

import os

stderr.writeLine "some stderr"
stderr.writeLine "some stderr2"
stdout.writeLine "some stdout2"
stderr.writeLine "some stderr3"
stderr.writeLine "some stderr4"

Results

Now, when I compile both, and run q_async.exe (on Windows), I'm getting output like below:

C:\prog\mana>q_async
O 1 s
E 1 s
O 1 o
X 0

If I remove fx from q_async, it's just hanging at some point, still not printing all output from q_outerr.

Do you have any idea what I might be doing wrong, and how I could make this work correctly, to display all stdout & stderr from q_outerr.nim?

@akavel
Copy link
Author

akavel commented Feb 13, 2020

Hmmmm; not sure but I might have fixed this by using waitFor instead of await, and making proc next non-async. Is that what I should be doing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant