Issue #13444: When stdout has been closed explicitly, we should not attempt to flush it at shutdown and print an error.

This also adds a test for issue #5319, whose resolution introduced the issue.
3 files changed