@@ -22,21 +22,37 @@ pub struct PollFd<'fd> {
22
22
impl < ' fd > PollFd < ' fd > {
23
23
/// Creates a new `PollFd` specifying the events of interest
24
24
/// for a given file descriptor.
25
- //
25
+ ///
26
+ /// # Examples
27
+ /// ```no_run
28
+ /// # use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
29
+ /// # use nix::{
30
+ /// # poll::{PollFd, PollFlags, poll},
31
+ /// # unistd::{pipe, read}
32
+ /// # };
33
+ /// let (r, w) = pipe().unwrap();
34
+ /// let r = unsafe { OwnedFd::from_raw_fd(r) };
35
+ /// let pfd = PollFd::new(&r.as_fd(), PollFlags::POLLIN);
36
+ /// let mut fds = [pfd];
37
+ /// poll(&mut fds, -1).unwrap();
38
+ /// let mut buf = [0u8; 80];
39
+ /// read(r.as_raw_fd(), &mut buf[..]);
40
+ /// ```
41
+ // Unlike I/O functions, constructors like this must take `AsFd` by
42
+ // reference. Otherwise, an `OwnedFd` argument would be dropped at the end
43
+ // of the method, leaving the structure referencing a closed file
44
+ // descriptor.
26
45
// Different from other I/O-safe interfaces, here, we have to take `AsFd`
27
46
// by reference to prevent the case where the `fd` is closed but it is
28
47
// still in use. For example:
29
48
//
30
49
// ```rust
31
- // let (reader, _) = pipe().unwrap();
32
- //
33
- // // If `PollFd::new()` takes `AsFd` by value, then `reader` will be consumed,
34
- // // but the file descriptor of `reader` will still be in use.
35
- // let pollfd = PollFd::new(reader, flag);
36
- //
50
+ // let (r, _) = pipe().unwrap();
51
+ // let reader: OwnedFd = unsafe { OwnedFd::from_raw_fd(r) };
52
+ // let pollfd = PollFd::new(reader, flag); // Drops the OwnedFd
37
53
// // Do something with `pollfd`, which uses the CLOSED fd.
38
54
// ```
39
- pub fn new < Fd : AsFd > ( fd : & ' fd Fd , events : PollFlags ) -> PollFd < ' fd > {
55
+ pub fn new < Fd : AsFd + ' fd > ( fd : & Fd , events : PollFlags ) -> PollFd < ' fd > {
40
56
PollFd {
41
57
pollfd : libc:: pollfd {
42
58
fd : fd. as_fd ( ) . as_raw_fd ( ) ,
0 commit comments