SundayMonday
SundayMonday

Reputation: 19727

basic popen3 syntax in ruby

Are there any differences between the following two uses of popen3?

html = ''
stdin, stdout, stderr = Open3.popen3("curl #{url}")
html << stdout.read

and

html = ''
Open3.popen3("curl #{url}") do |stdin, stdout, stderr, wait_thr|
  result << stdout.read
end

I'm wondering if the second syntax causes some thread to block. I'm fairly new to asynchronous code so any insights are greatly appreciated!

Upvotes: 1

Views: 727

Answers (2)

Tilo
Tilo

Reputation: 33722

The reason you are experiencing a blocking behavior is because you did not close stdin to the program (curl) you opened via popen3 -- so curl is still waiting for your input.

You should close stdin explicitly via stdin.close after you are done sending data to the program, otherwise it will keep expecting input on stdin, and popen3 will hang.

 stdin.close    # always close your stdin after you are done sending commands/data
                # or popen3 will appear to hang

Upvotes: 1

megas
megas

Reputation: 21791

In the first form you should explicitly close stdin, stdout and stderr.

Upvotes: 1

Related Questions