Skip to content

Commit

Permalink
Close Tokio stream
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-smoktal committed May 22, 2024
1 parent 4d15a43 commit 2185c7a
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "async-send-fd"
version = "1.1.0"
version = "1.2.0"
edition = "2021"
authors = ["Alexander Smoktal [https://github.com/alexander-smoktal]"]
license = "MIT"
Expand All @@ -20,6 +20,7 @@ smol = ["dep:smol"]
passfd = "0.1"
tokio = { version = "1", features = ["net", "io-util"], optional = true }
smol = { version = "2", optional = true }
nix = "0.28"

[dev-dependencies]
tempdir = "0.3"
Expand Down
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ If you make a Tokio [UnixStream](https://docs.rs/tokio/latest/tokio/net/struct.U
Smol [UnixStream](https://docs.rs/smol/2.0.0/smol/net/unix/struct.UnixStream.html) does it automatically if created using `UnixStream::from(Async::new(stream))`

## Transfering socket pair ownership
Sending a descriptor doesn't close the local copy, which leads to having the socket being opened by the sender until it shuts down.
If you want socket pair receivers to detect peer shutdown, you have to close local sockets after sending them.
Use [UnixStream::poll_shutdown()](https://docs.rs/tokio/latest/tokio/net/struct.UnixStream.html#method.poll_shutdown) for Tokio streams, or [UnixStream::shutdown()](https://docs.rs/smol/2.0.0/smol/net/unix/struct.UnixStream.html#method.shutdown) for Smol.
Note: the library closes Tokio stream if sent into another process.

## Features
- `tokio` - for Tokio support
Expand Down
11 changes: 11 additions & 0 deletions src/tokio_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::{
net::UnixStream as OsUnixStream,
prelude::{FromRawFd, IntoRawFd},
},
process,
};

use tokio::{
Expand Down Expand Up @@ -56,6 +57,16 @@ impl AsyncSendFd for UnixStream {
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
continue;
}
Ok(_) => {
// Try to close the FD if sent into another process
if let Some(pid) = self.peer_cred().ok().and_then(|creds| creds.pid()) {
if pid as u32 != process::id() {
nix::unistd::close(fd)?;
}
}

return Ok(());
}
r => return r,
}
}
Expand Down

0 comments on commit 2185c7a

Please sign in to comment.