@@ -18,7 +18,9 @@ use std::{
18
18
use inotify_sys as ffi;
19
19
use libc:: {
20
20
F_GETFL ,
21
+ F_SETFD ,
21
22
F_SETFL ,
23
+ FD_CLOEXEC ,
22
24
O_NONBLOCK ,
23
25
fcntl,
24
26
} ;
@@ -82,23 +84,25 @@ impl Inotify {
82
84
/// [`IN_CLOEXEC`]: ../inotify_sys/constant.IN_CLOEXEC.html
83
85
/// [`IN_NONBLOCK`]: ../inotify_sys/constant.IN_NONBLOCK.html
84
86
pub fn init ( ) -> io:: Result < Inotify > {
87
+ // Initialize inotify and set CLOEXEC and NONBLOCK flags.
88
+ //
89
+ // NONBLOCK is needed, because `Inotify` manages blocking behavior for
90
+ // the API consumer, and the way we do that is to make everything non-
91
+ // blocking by default and later override that as required.
92
+ //
93
+ // CLOEXEC prevents leaking file descriptors to processes executed by
94
+ // this process and seems to be a best practice. I don't grasp this
95
+ // issue completely and failed to find any authoritative sources on the
96
+ // topic. There's some discussion in the open(2) and fcntl(2) man pages,
97
+ // but I didn't find that helpful in understanding the issue of leaked
98
+ // file descriptors. For what it's worth, there's a Rust issue about
99
+ // this:
100
+ // https://github.com/rust-lang/rust/issues/12148
85
101
let fd = unsafe {
86
- // Initialize inotify and pass both `IN_CLOEXEC` and `IN_NONBLOCK`.
87
- //
88
- // `IN_NONBLOCK` is needed, because `Inotify` manages blocking
89
- // behavior for the API consumer, and the way we do that is to make
90
- // everything non-blocking by default and later override that as
91
- // required.
92
- //
93
- // Passing `IN_CLOEXEC` prevents leaking file descriptors to
94
- // processes executed by this process and seems to be a best
95
- // practice. I don't grasp this issue completely and failed to find
96
- // any authoritative sources on the topic. There's some discussion in
97
- // the open(2) and fcntl(2) man pages, but I didn't find that
98
- // helpful in understanding the issue of leaked file descriptors.
99
- // For what it's worth, there's a Rust issue about this:
100
- // https://github.com/rust-lang/rust/issues/12148
101
- ffi:: inotify_init1 ( ffi:: IN_CLOEXEC | ffi:: IN_NONBLOCK )
102
+ let fd = ffi:: inotify_init ( ) ;
103
+ fcntl ( fd, F_SETFD , FD_CLOEXEC ) ;
104
+ fcntl ( fd, F_SETFL , O_NONBLOCK ) ;
105
+ fd
102
106
} ;
103
107
104
108
match fd {
0 commit comments