This ensures flush() is only called if the stream is open, and logs (but ignores) any exceptions during flush. This should prevent the "Bad file descriptor" error.
I see this error a lot on a rak unit, I dont know this is the way but .. you be the judge.