Struct Receiver
pub struct Receiver { /* private fields */ }
Reading end of a Unix pipe.
It can be constructed from a FIFO file with OpenOptions::open_receiver.
Examples
Receiving messages from a named pipe in a loop:
use tokio::net::unix::pipe;
use tokio::io::{self, AsyncReadExt};
const FIFO_NAME: &str = "path/to/a/fifo";
# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let mut rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?;
loop {
let mut msg = vec![0; 256];
match rx.read_exact(&mut msg).await {
Ok(_) => {
/* handle the message */
}
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
// Writing end has been closed, we should reopen the pipe.
rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?;
}
Err(e) => return Err(e.into()),
}
}
# }
On Linux, you can use a Receiver in read-write access mode to implement
resilient reading from a named pipe. Unlike Receiver opened in read-only
mode, read from a pipe in read-write mode will not fail with UnexpectedEof
when the writing end is closed. This way, a Receiver can asynchronously
wait for the next writer to open the pipe.
You should not use functions waiting for EOF such as read_to_end with
a Receiver in read-write access mode, since it may wait forever.
Receiver in this mode also holds an open writing end, which prevents
receiving EOF.
To set the read-write access mode you can use OpenOptions::read_write.
Note that using read-write access mode with FIFO files is not defined by
the POSIX standard and it is only guaranteed to work on Linux.
use tokio::net::unix::pipe;
use tokio::io::AsyncReadExt;
# use std::error::Error;
const FIFO_NAME: &str = "path/to/a/fifo";
# async fn dox() -> Result<(), Box<dyn Error>> {
let mut rx = pipe::OpenOptions::new()
.read_write(true)
.open_receiver(FIFO_NAME)?;
loop {
let mut msg = vec![0; 256];
rx.read_exact(&mut msg).await?;
/* handle the message */
}
# }
Implementations
impl Receiver
fn from_file(file: File) -> Result<Receiver>Creates a new
Receiverfrom aFile.This function is intended to construct a pipe from a
Filerepresenting a special FIFO file. It will check if the file is a pipe and has read access, set it in non-blocking mode and perform the conversion.Errors
Fails with
io::ErrorKind::InvalidInputif the file is not a pipe or it does not have read access. Also fails with any standard OS error if it occurs.Panics
This function panics if it is not called from within a runtime with IO enabled.
The runtime is usually set implicitly when this function is called from a future driven by a tokio runtime, otherwise runtime can be set explicitly with
Runtime::enterfunction.fn from_owned_fd(owned_fd: OwnedFd) -> Result<Receiver>Creates a new
Receiverfrom anOwnedFd.This function is intended to construct a pipe from an
OwnedFdrepresenting an anonymous pipe or a special FIFO file. It will check if the file descriptor is a pipe and has read access, set it in non-blocking mode and perform the conversion.Errors
Fails with
io::ErrorKind::InvalidInputif the file descriptor is not a pipe or it does not have read access. Also fails with any standard OS error if it occurs.Panics
This function panics if it is not called from within a runtime with IO enabled.
The runtime is usually set implicitly when this function is called from a future driven by a tokio runtime, otherwise runtime can be set explicitly with
Runtime::enterfunction.fn from_file_unchecked(file: File) -> Result<Receiver>Creates a new
Receiverfrom aFilewithout checking pipe properties.This function is intended to construct a pipe from a File representing a special FIFO file. The conversion assumes nothing about the underlying file; it is left up to the user to make sure it is opened with read access, represents a pipe and is set in non-blocking mode.
Examples
use tokio::net::unix::pipe; use std::fs::OpenOptions; use std::os::unix::fs::{FileTypeExt, OpenOptionsExt}; # use std::error::Error; const FIFO_NAME: &str = "path/to/a/fifo"; # async fn dox() -> Result<(), Box<dyn Error>> { let file = OpenOptions::new() .read(true) .custom_flags(libc::O_NONBLOCK) .open(FIFO_NAME)?; if file.metadata()?.file_type().is_fifo() { let rx = pipe::Receiver::from_file_unchecked(file)?; /* use the Receiver */ } # Ok(()) # }Panics
This function panics if it is not called from within a runtime with IO enabled.
The runtime is usually set implicitly when this function is called from a future driven by a tokio runtime, otherwise runtime can be set explicitly with
Runtime::enterfunction.fn from_owned_fd_unchecked(owned_fd: OwnedFd) -> Result<Receiver>Creates a new
Receiverfrom anOwnedFdwithout checking pipe properties.This function is intended to construct a pipe from an
OwnedFdrepresenting an anonymous pipe or a special FIFO file. The conversion assumes nothing about the underlying pipe; it is left up to the user to make sure that the file descriptor represents the reading end of a pipe and the pipe is set in non-blocking mode.Panics
This function panics if it is not called from within a runtime with IO enabled.
The runtime is usually set implicitly when this function is called from a future driven by a tokio runtime, otherwise runtime can be set explicitly with
Runtime::enterfunction.async fn ready(&self, interest: Interest) -> Result<Ready>Waits for any of the requested ready states.
This function can be used instead of
readable()to check the returned ready set forReady::READABLEandReady::READ_CLOSEDevents.The function may complete without the pipe being ready. This is a false-positive and attempting an operation will return with
io::ErrorKind::WouldBlock. The function can also return with an emptyReadyset, so you should always check the returned value and possibly wait again if the requested states are not set.Cancel safety
This method is cancel safe. Once a readiness event occurs, the method will continue to return immediately until the readiness event is consumed by an attempt to read that fails with
WouldBlockorPoll::Pending.async fn readable(&self) -> Result<()>Waits for the pipe to become readable.
This function is equivalent to
ready(Interest::READABLE)and is usually paired withtry_read().Examples
use tokio::net::unix::pipe; use std::io; #[tokio::main] async fn main() -> io::Result<()> { // Open a reading end of a fifo let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?; let mut msg = vec![0; 1024]; loop { // Wait for the pipe to be readable rx.readable().await?; // Try to read data, this may still fail with `WouldBlock` // if the readiness event is a false positive. match rx.try_read(&mut msg) { Ok(n) => { msg.truncate(n); break; } Err(e) if e.kind() == io::ErrorKind::WouldBlock => { continue; } Err(e) => { return Err(e.into()); } } } println!("GOT = {:?}", msg); Ok(()) }fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<Result<()>>Polls for read readiness.
If the pipe is not currently ready for reading, this method will store a clone of the
Wakerfrom the providedContext. When the pipe becomes ready for reading,Waker::wakewill be called on the waker.Note that on multiple calls to
poll_read_readyorpoll_read, only theWakerfrom theContextpassed to the most recent call is scheduled to receive a wakeup.This function is intended for cases where creating and pinning a future via
readableis not feasible. Where possible, usingreadableis preferred, as this supports polling from multiple tasks at once.Return value
The function returns:
Poll::Pendingif the pipe is not ready for reading.Poll::Ready(Ok(()))if the pipe is ready for reading.Poll::Ready(Err(e))if an error is encountered.
Errors
This function may encounter any standard I/O error except
WouldBlock.fn try_read(&self, buf: &mut [u8]) -> Result<usize>Tries to read data from the pipe into the provided buffer, returning how many bytes were read.
Reads any pending data from the pipe but does not wait for new data to arrive. On success, returns the number of bytes read. Because
try_read()is non-blocking, the buffer does not have to be stored by the async task and can exist entirely on the stack.Usually
readable()is used with this function.Return
If data is successfully read,
Ok(n)is returned, wherenis the number of bytes read. Ifnis0, then it can indicate one of two scenarios:- The pipe's writing end is closed and will no longer write data.
- The specified buffer was 0 bytes in length.
If the pipe is not ready to read data,
Err(io::ErrorKind::WouldBlock)is returned.Notes
To avoid unnecessary syscalls, this will only attempt the read operation if the OS has informed Tokio that this pipe has become readable. Because of this,
try_read()may fail with aWouldBlockerror if Tokio has not yet heard from the OS that this pipe has become readable.Examples
use tokio::net::unix::pipe; use std::io; #[tokio::main] async fn main() -> io::Result<()> { // Open a reading end of a fifo let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?; let mut msg = vec![0; 1024]; loop { // Wait for the pipe to be readable rx.readable().await?; // Try to read data, this may still fail with `WouldBlock` // if the readiness event is a false positive. match rx.try_read(&mut msg) { Ok(n) => { msg.truncate(n); break; } Err(e) if e.kind() == io::ErrorKind::WouldBlock => { continue; } Err(e) => { return Err(e.into()); } } } println!("GOT = {:?}", msg); Ok(()) }fn try_read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>Tries to read data from the pipe into the provided buffers, returning how many bytes were read.
Data is copied to fill each buffer in order, with the final buffer written to possibly being only partially filled. This method behaves equivalently to a single call to
try_read()with concatenated buffers.Reads any pending data from the pipe but does not wait for new data to arrive. On success, returns the number of bytes read. Because
try_read_vectored()is non-blocking, the buffer does not have to be stored by the async task and can exist entirely on the stack.Usually,
readable()is used with this function.Return
If data is successfully read,
Ok(n)is returned, wherenis the number of bytes read.Ok(0)indicates the pipe's writing end is closed and will no longer write data. If the pipe is not ready to read dataErr(io::ErrorKind::WouldBlock)is returned.Notes
To avoid unnecessary syscalls, this will only attempt the read operation if the OS has informed Tokio that this pipe has become readable. Because of this,
try_read_vectored()may fail with aWouldBlockerror if Tokio has not yet heard from the OS that this pipe has become readable.Examples
use tokio::net::unix::pipe; use std::io; #[tokio::main] async fn main() -> io::Result<()> { // Open a reading end of a fifo let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?; loop { // Wait for the pipe to be readable rx.readable().await?; // Creating the buffer **after** the `await` prevents it from // being stored in the async task. let mut buf_a = [0; 512]; let mut buf_b = [0; 1024]; let mut bufs = [ io::IoSliceMut::new(&mut buf_a), io::IoSliceMut::new(&mut buf_b), ]; // Try to read data, this may still fail with `WouldBlock` // if the readiness event is a false positive. match rx.try_read_vectored(&mut bufs) { Ok(0) => break, Ok(n) => { println!("read {} bytes", n); } Err(e) if e.kind() == io::ErrorKind::WouldBlock => { continue; } Err(e) => { return Err(e.into()); } } } Ok(()) }fn try_io<R>(&self, f: impl FnOnce() -> Result<R>) -> Result<R>Tries to read to the socket using a user-provided IO operation.
If the socket is ready, the provided closure is called. The closure should attempt to perform IO operation on the socket by manually calling the appropriate syscall. If the operation fails because the socket is not actually ready, then the closure should return a
WouldBlockerror and the readiness flag is cleared. The return value of the closure is then returned bytry_io.If the socket is not ready, then the closure is not called and a
WouldBlockerror is returned.The closure should only return a
WouldBlockerror if it has performed an IO operation on the socket that failed due to the socket not being ready. Returning aWouldBlockerror in any other situation will incorrectly clear the readiness flag, which can cause the socket to behave incorrectly.The closure should not perform the IO operation using any of the methods defined on the Tokio
pipe::Receivertype, as this will mess with the readiness flag and can cause the socket to behave incorrectly.Usually,
readable()orready()is used with this function.fn try_read_buf<B: BufMut>(&self, buf: &mut B) -> Result<usize>Tries to read data from the pipe into the provided buffer, advancing the buffer's internal cursor, returning how many bytes were read.
Reads any pending data from the pipe but does not wait for new data to arrive. On success, returns the number of bytes read. Because
try_read_buf()is non-blocking, the buffer does not have to be stored by the async task and can exist entirely on the stack.Usually,
readable()orready()is used with this function.Return
If data is successfully read,
Ok(n)is returned, wherenis the number of bytes read.Ok(0)indicates the pipe's writing end is closed and will no longer write data. If the pipe is not ready to read dataErr(io::ErrorKind::WouldBlock)is returned.Notes
To avoid unnecessary syscalls, this will only attempt the read operation if the OS has informed Tokio that this pipe has become readable. Because of this,
try_read_buf()may fail with aWouldBlockerror if Tokio has not yet heard from the OS that this pipe has become readable.Examples
use tokio::net::unix::pipe; use std::io; #[tokio::main] async fn main() -> io::Result<()> { // Open a reading end of a fifo let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?; loop { // Wait for the pipe to be readable rx.readable().await?; let mut buf = Vec::with_capacity(4096); // Try to read data, this may still fail with `WouldBlock` // if the readiness event is a false positive. match rx.try_read_buf(&mut buf) { Ok(0) => break, Ok(n) => { println!("read {} bytes", n); } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { continue; } Err(e) => { return Err(e.into()); } } } Ok(()) }fn into_blocking_fd(self) -> Result<OwnedFd>Converts the pipe into an
OwnedFdin blocking mode.This function will deregister this pipe end from the event loop, set it in blocking mode and perform the conversion.
fn into_nonblocking_fd(self) -> Result<OwnedFd>Converts the pipe into an
OwnedFdin nonblocking mode.This function will deregister this pipe end from the event loop and perform the conversion. Returned file descriptor will be in nonblocking mode.
Trait Implementations
impl AsFd for Receiver
fn as_fd(&self) -> BorrowedFd<'_>
impl AsRawFd for Receiver
fn as_raw_fd(&self) -> RawFd
impl AsyncRead for Receiver
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<Result<()>>
impl Debug for Receiver
fn fmt(&self, f: &mut Formatter<'_>) -> Result
Auto Trait Implementations
impl !Freeze for Receiver
impl RefUnwindSafe for Receiver
impl Send for Receiver
impl Sync for Receiver
impl Unpin for Receiver
impl UnsafeUnpin for Receiver
impl UnwindSafe for Receiver
Blanket Implementations
impl<R> AsyncReadExt for Receiver
where
R: AsyncRead + ?Sized,
impl<T> Any for Receiver
where
T: 'static + ?Sized,
fn type_id(&self) -> TypeId
impl<T> Borrow<T> for Receiver
where
T: ?Sized,
fn borrow(&self) -> &T
impl<T> BorrowMut<T> for Receiver
where
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
impl<T> From<T> for Receiver
fn from(t: T) -> TReturns the argument unchanged.
impl<T, U> Into<U> for Receiver
where
U: From<T>,
fn into(self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom<U> for Receiver
where
U: Into<T>,
type Error = never;fn try_from(value: U) -> Result<T, never>
impl<T, U> TryInto<U> for Receiver
where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error;fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>