Skip to content

Instantly share code, notes, and snippets.

@rorymckinley
Created December 5, 2020 11:46
Show Gist options
  • Save rorymckinley/fe7a78e3022a936275664af9311926a5 to your computer and use it in GitHub Desktop.
Save rorymckinley/fe7a78e3022a936275664af9311926a5 to your computer and use it in GitHub Desktop.
Odd Behaviour of STDOUT .sync
#!/usr/bin/env ruby
STDOUT.sync = true if ARGV[0] == 'sync'
i = 0
while i < 5 do
i = i + 1
STDERR.puts "I ERR: #{i}"
STDOUT.puts "I OUT: #{i}"
end
STDERR.puts "STDOUT sync status: #{STDOUT.sync}"
# `./test.rb` produces the following behaviour (expected because Ruby flushes immediately as STDOUT is a tty)
# I ERR: 1
# I OUT: 1
# I ERR: 2
# I OUT: 2
# I ERR: 3
# I OUT: 3
# I ERR: 4
# I OUT: 4
# I ERR: 5
# I OUT: 5
# STDOUT sync status: false
#`./test.rb | awk '{printf("Via a non-tty: %s\n", $0)}'` produces the below (also expected, as STDOUT is no longer a tty)
# I ERR: 1
# I ERR: 2
# I ERR: 3
# I ERR: 4
# I ERR: 5
# STDOUT sync status: false
# Via a non-tty: I OUT: 1
# Via a non-tty: I OUT: 2
# Via a non-tty: I OUT: 3
# Via a non-tty: I OUT: 4
# Via a non-tty: I OUT: 5
#`./test.rb | awk '{printf("Via a non-tty: %s\n", $0)}'` produces unexpected behaviour (STDOUT.sync is true, so ito
# flushing, behaviour should be the same as when STDOUT was a tty.
# I ERR: 1
# I ERR: 2
# I ERR: 3
# I ERR: 4
# I ERR: 5
# STDOUT sync status: true
# Via a non-tty: I OUT: 1
# Via a non-tty: I OUT: 2
# Via a non-tty: I OUT: 3
# Via a non-tty: I OUT: 4
# Via a non-tty: I OUT: 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment