1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
use std::io;
use std::os::unix::io::{RawFd, FromRawFd, AsRawFd, IntoRawFd};
use nix;
use nix::fcntl::{fcntl, FcntlArg};
use nix::unistd::dup;
use libc;
pub enum Stdio {
Pipe,
Inherit,
Null,
Fd(Closing),
}
pub enum Fd {
ReadPipe,
WritePipe,
Inherit,
ReadNull,
WriteNull,
Fd(Closing),
RawFd(RawFd),
}
pub struct Closing(RawFd);
impl Stdio {
pub fn piped() -> Stdio { Stdio::Pipe }
pub fn inherit() -> Stdio { Stdio::Inherit }
pub fn null() -> Stdio { Stdio::Null }
pub fn to_fd(self, write: bool) -> Fd {
match (self, write) {
(Stdio::Fd(x), _) => Fd::Fd(x),
(Stdio::Pipe, false) => Fd::ReadPipe,
(Stdio::Pipe, true) => Fd::WritePipe,
(Stdio::Inherit, _) => Fd::Inherit,
(Stdio::Null, false) => Fd::ReadNull,
(Stdio::Null, true) => Fd::WriteNull,
}
}
pub fn dup_file<F: AsRawFd>(file: &F) -> io::Result<Stdio> {
match fcntl(file.as_raw_fd(), FcntlArg::F_DUPFD_CLOEXEC(3)) {
Ok(fd) => Ok(Stdio::Fd(Closing(fd))),
Err(nix::Error::Sys(errno)) => {
return Err(io::Error::from_raw_os_error(errno as i32));
}
Err(nix::Error::InvalidPath) => unreachable!(),
}
}
pub fn from_file<F: IntoRawFd>(file: F) -> Stdio {
Stdio::Fd(Closing(file.into_raw_fd()))
}
}
impl Fd {
pub fn piped_read() -> Fd { Fd::ReadPipe }
pub fn piped_write() -> Fd { Fd::WritePipe }
pub fn inherit() -> Fd { Fd::Inherit }
pub fn read_null() -> Fd { Fd::ReadNull }
pub fn write_null() -> Fd { Fd::WriteNull }
pub fn dup_file<F: AsRawFd>(file: &F) -> io::Result<Fd> {
match dup(file.as_raw_fd()) {
Ok(fd) => Ok(Fd::Fd(Closing(fd))),
Err(nix::Error::Sys(errno)) => {
return Err(io::Error::from_raw_os_error(errno as i32));
}
Err(nix::Error::InvalidPath) => unreachable!(),
}
}
pub fn from_file<F: IntoRawFd>(file: F) -> Fd {
Fd::Fd(Closing(file.into_raw_fd()))
}
}
impl Closing {
pub fn new(fd: RawFd) -> Closing {
Closing(fd)
}
}
impl FromRawFd for Stdio {
unsafe fn from_raw_fd(fd: RawFd) -> Stdio {
return Stdio::Fd(Closing(fd));
}
}
impl FromRawFd for Fd {
unsafe fn from_raw_fd(fd: RawFd) -> Fd {
return Fd::Fd(Closing(fd));
}
}
impl AsRawFd for Closing {
fn as_raw_fd(&self) -> RawFd {
return self.0;
}
}
impl Drop for Closing {
fn drop(&mut self) {
unsafe {
libc::close(self.0);
}
}
}