When parsing output of pipes connect both STDOUT and STDERR

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-11-21

I wanted to parse the output of a subprocess (i.e. I was looking for the content "listening")

I had the following code:

pipe_read, pipe_write = IO.pipe
pid = Process.spawn(
  start_vim_server,
  in: pipe_read,
  out: pipe_write
)

# pipe_read.gets never had any content
until (line = pipe_read.gets) =~ /listening/i
  puts "waiting #{line}"
  sleep 0.1
end

When I ran it, I noticed the output "listening" appearing on the terminal, but pipe_read had 0 lines, therefore my loop never even ran.

The fix was to pay attention to STDERR as well:

pipe_read, pipe_write = IO.pipe
pid = Process.spawn(
  start_vim_server,
  in: pipe_read,
  err: pipe_write,
  out: pipe_write
)