Skip to content

Commit

Permalink
Rollup merge of #101404 - joboet:always_cleanup_stdout, r=joshtriplett
Browse files Browse the repository at this point in the history
Fix cleanup for uninitialized stdout

Fixes #101375 by disabling buffering even if the buffer was not initialized yet.
  • Loading branch information
matthiaskrgr authored Sep 5, 2022
2 parents 42770d1 + 774cadf commit 6653d70
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions library/std/src/io/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,15 +607,24 @@ pub fn stdout() -> Stdout {
}
}

// Flush the data and disable buffering during shutdown
// by replacing the line writer by one with zero
// buffering capacity.
pub fn cleanup() {
// Flush the data and disable buffering during shutdown
// by replacing the line writer by one with zero
// buffering capacity.
// We use try_lock() instead of lock(), because someone
// might have leaked a StdoutLock, which would
// otherwise cause a deadlock here.
if let Some(lock) = STDOUT.get().and_then(ReentrantMutex::try_lock) {
*lock.borrow_mut() = LineWriter::with_capacity(0, stdout_raw());
let mut initialized = false;
let stdout = STDOUT.get_or_init(|| {
initialized = true;
ReentrantMutex::new(RefCell::new(LineWriter::with_capacity(0, stdout_raw())))
});

if !initialized {
// The buffer was previously initialized, overwrite it here.
// We use try_lock() instead of lock(), because someone
// might have leaked a StdoutLock, which would
// otherwise cause a deadlock here.
if let Some(lock) = stdout.try_lock() {
*lock.borrow_mut() = LineWriter::with_capacity(0, stdout_raw());
}
}
}

Expand Down

0 comments on commit 6653d70

Please sign in to comment.