[Gambas-user] Blocking read from a Process you had to write to

Tobias Boege taboege at gmail.com
Mon Mar 18 23:04:23 CET 2019


Hi,

the task is to start a process, write something to its input, then read
all its output. This should happen in a blocking fashion, i.e. I want the
output of the process to be the return value of my function. The process,
after receiving its input will immediately produce its output. Hence I
do *not* want to use a Read event, purely because it shouldn't be necessary
and requires a sort of busy-waiting in my function until the output has
been accumulated.

What I normally try first is:

  Dim sInput As String = "hello" ' might be binary data!
  Dim aCmd As String[] = ["cat", "-"]
  Dim hProc As Process, sOut As String

  hProc = Exec aCmd For Read Write
  Write #hProc, sInput
  hProc.CloseInput()
  hProc.Wait()
  sOut = Read #hProc, Lof(hProc)
  Return sOut

When the Wait call returns, I've got a Lof() of zero, but apparently
hProc.Value is also zero, i.e. success, so where's my output?
Independently of that, it might be wise to read output continuously
to avoid the pipe buffer filling up, so I try:

  hProc = Exec aCmd For Read Write
  Write #hProc, sInput
  hProc.CloseInput()
  Wait
  While (hProc.State = hProc.Running) Or Lof(hProc)
    sBuf = Read #hProc, -4096
    sOut &= sBuf
    Wait
  Wend

I'm unsure about the Waits here. At least one of them ought to be necessary.
This dies with "Stream is closed" at the Lof() call in the While condition
after everything has been read. I guess I can see that. But if I Wait a
positive amount of time inside the While loop, e.g. "Wait 0.1", it works.

How is it done properly? I really just want an "Exec ... To sOut", but with
the option to pipe something into the process when it starts.

Regards,
Tobi

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk


More information about the User mailing list