Reading from FileDescriptor without blocking the Fiber

I’m trying to spawn a bunch of fibers, where each one spawn a process and pipes the output of said process to stdout, with a prefix, the code inside the loop is something along the lines of:

spawn do
    STDOUT.printf("[%s] Starting\n", command_name)
    out_read, out_write = IO.pipe
    err_read, err_write = IO.pipe
    proc = Process.new(
      cmd.command,
      args,
      chdir: chdir,
      input: Process::Redirect::Close,
      output: out_write,
      error: err_write
    )
    while !out_read.closed?
      STDOUT.printf("[%s][stdout] %s", command_name, out_read.gets(chomp: false))
      STDERR.printf("[%s][stderr] %s", command_name, err_read.gets(chomp: false))
    end
  end

The problem is that err_read.gets(chomp: false) blocks the process completely. Is there any way of just skipping that line if there isn’t any data in err_read

You’ll need two fibers, one for reading each stdout and stderr.

1 Like

Thanks for your response !

How would I go about closing the fibers down if they are stuck listening to the channels though ?

EDIT: they are automatically closed, I don’t need to deal with this !