-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Redirecting standard streams feels more hackish/clumsy than it needs to be #14580
Comments
I believe this can be simplified quite a lot. But still, cloning standard streams is an implementation detail of the Crystal runtime and should be unnoticable to the user (as far as possible). |
Simplified code to redirect stderr: redirect = File.open("./stderr", "w+")
redirect.close_on_finalize = false
STDERR.reopen(redirect)
if STDERR.fd != 2
IO::FileDescriptor.new(2, close_on_finalize: false).reopen(redirect)
end This should achieve pretty much the same as the example from the OP. Another advice would be to make this redirect conditional on |
This sounds like a very ideal approach, and what I expected when I first tried implementing this a number of months ago. Finding that
I had never thought about checking for a TTY... I'll add that to my original code, thank you ^_^ |
This is something that came up as a discussion on my Fediverse account earlier.
Sometimes a program may need to redirect stdin/stdout/stderr programmatically at runtime, but it feels like the process to do this in Crystal is more clumsy than it needs to be. The fact that Crystal will change its own stderr's FD to something other than 2 just sorta complicates matters, leaving a program dealing with two separate stderr FD's.
The use-case where I encountered this was with my Benben program, where a C library I bind will sometimes print to stderr with no way to change this behavior via its API. This then corrupts up my TUI display, which is annoying. So I instead redirect both FD 2 and FD 5 to a file, then keeps the original real stderr in memory to prevent it from being GC'd. Doing so requires some code similar to this:
The full original code where I do this in Benben can be found here.
Having a much nicer way to do this in the stdlib, where I don't have to bind
dup()
and create a newIO::FileDescriptor
would be great. Maybe something that accepts a block?The text was updated successfully, but these errors were encountered: