Skip to content

Commit ff124c6

Browse files
authored
Rollup merge of #101404 - joboet:always_cleanup_stdout, r=joshtriplett
Fix cleanup for uninitialized stdout Fixes #101375 by disabling buffering even if the buffer was not initialized yet.
2 parents 957b44a + 774cadf commit ff124c6

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

library/std/src/io/stdio.rs

+17-8
Original file line numberDiff line numberDiff line change
@@ -607,15 +607,24 @@ pub fn stdout() -> Stdout {
607607
}
608608
}
609609

610+
// Flush the data and disable buffering during shutdown
611+
// by replacing the line writer by one with zero
612+
// buffering capacity.
610613
pub fn cleanup() {
611-
// Flush the data and disable buffering during shutdown
612-
// by replacing the line writer by one with zero
613-
// buffering capacity.
614-
// We use try_lock() instead of lock(), because someone
615-
// might have leaked a StdoutLock, which would
616-
// otherwise cause a deadlock here.
617-
if let Some(lock) = STDOUT.get().and_then(ReentrantMutex::try_lock) {
618-
*lock.borrow_mut() = LineWriter::with_capacity(0, stdout_raw());
614+
let mut initialized = false;
615+
let stdout = STDOUT.get_or_init(|| {
616+
initialized = true;
617+
ReentrantMutex::new(RefCell::new(LineWriter::with_capacity(0, stdout_raw())))
618+
});
619+
620+
if !initialized {
621+
// The buffer was previously initialized, overwrite it here.
622+
// We use try_lock() instead of lock(), because someone
623+
// might have leaked a StdoutLock, which would
624+
// otherwise cause a deadlock here.
625+
if let Some(lock) = stdout.try_lock() {
626+
*lock.borrow_mut() = LineWriter::with_capacity(0, stdout_raw());
627+
}
619628
}
620629
}
621630

0 commit comments

Comments
 (0)