From 2a56c0f62a353b5ca1eac4f431d9d9b6095c27d2 Mon Sep 17 00:00:00 2001 From: Max Brunsfeld Date: Tue, 1 Mar 2022 14:33:12 -0800 Subject: [PATCH 1/2] Return an error when flushing a PipeWriter whose reader is closed Co-Authored-By: Nathan Sobo --- src/writer.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/writer.rs b/src/writer.rs index f32c3b2..3518c18 100644 --- a/src/writer.rs +++ b/src/writer.rs @@ -100,6 +100,16 @@ impl PipeWriter { } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + if Arc::strong_count(&self.state) == 1 { + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::BrokenPipe, + format!( + "{}: PipeWriter: The channel is closed", + env!("CARGO_PKG_NAME") + ), + ))); + } + let mut state = match self.state.lock() { Ok(s) => s, Err(err) => { From 82d00a04211cf4e1236029aa03e6b6ce2a74c553 Mon Sep 17 00:00:00 2001 From: Max Brunsfeld Date: Tue, 1 Mar 2022 14:43:52 -0800 Subject: [PATCH 2/2] Close pipe when dropping reader or writer --- src/reader.rs | 6 ++++++ src/writer.rs | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/src/reader.rs b/src/reader.rs index ca5df0f..86d967a 100644 --- a/src/reader.rs +++ b/src/reader.rs @@ -124,3 +124,9 @@ impl futures::io::AsyncRead for PipeReader { self.poll_read(cx, buf) } } + +impl Drop for PipeReader { + fn drop(&mut self) { + self.close().ok(); + } +} diff --git a/src/writer.rs b/src/writer.rs index 3518c18..2d1ac16 100644 --- a/src/writer.rs +++ b/src/writer.rs @@ -148,6 +148,12 @@ impl PipeWriter { } } +impl Drop for PipeWriter { + fn drop(&mut self) { + self.close().ok(); + } +} + #[cfg(feature = "tokio")] impl tokio::io::AsyncWrite for PipeWriter { fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll> {