crystal-lang / crystal

The Crystal Programming Language
https://crystal-lang.org
Apache License 2.0
19.26k stars 1.61k forks source link

Console streams are blocking on Windows #14576

Open straight-shoota opened 2 months ago

straight-shoota commented 2 months ago

This has been mentioned before but I don't think there's a dedicated issue for it.

The standard streams on Windows are blocking. On Unix systems, on the other hand, they are non-blocking for TTYs. It allows to continue other fibers while waiting on IO. This is particularly relevant for STDIN.

For example, the following program prints the current time and updates it every second, while pressing enter aborts.

spawn do
  loop do
    print Time.utc.to_s("%H:%M:%S\r")
    sleep 1.second
  end
end

STDIN.gets

On Windows, it doesn't print anything because STDIN.gets is blocking and the loop fiber never gets a chance to execute.

We should have the same behaviour as on Unix. I'm not sure how we can best achieve it.

HertzDevil commented 2 months ago

IIRC Win32 console handles do not support overlapped I/O, so any kind of asynchronous capability requires threads; the standard input and output streams are not opened with FILE_FLAG_OVERLAPPED, and additional console handles opened using CreateFile do not respect that flag