-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfifo.rs
154 lines (132 loc) · 4.51 KB
/
fifo.rs
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use std::fs::{remove_file, File, OpenOptions};
use std::os::unix::prelude::{AsRawFd, OpenOptionsExt};
use crate::error::SimulatorError;
use nix::fcntl::{self, FcntlArg, FdFlag, OFlag};
use nix::libc::O_NONBLOCK;
use nix::sys::stat;
use nix::unistd::mkfifo;
pub struct Fifo {
_name: String,
_in: Option<File>,
_out: Option<File>,
}
impl Fifo {
fn open_fifo(path: &str) -> Result<(), SimulatorError> {
match mkfifo(
path,
stat::Mode::S_IRWXU | stat::Mode::S_IRWXG | stat::Mode::S_IRWXO,
) {
Ok(_) | Err(nix::errno::Errno::EEXIST) => Ok(()),
Err(e) => Err(SimulatorError::FifoCreationError(format!("{e}"))),
}
}
fn make_blocking(fd: i32) -> Result<(), SimulatorError> {
let mut flags = OFlag::from_bits_truncate(fcntl::fcntl(fd, FcntlArg::F_GETFL).unwrap());
flags.remove(OFlag::O_NONBLOCK);
fcntl::fcntl(fd, FcntlArg::F_SETFL(flags))
.map_err(|e| SimulatorError::FifoCreationError(format!("{e}")))?;
Ok(())
}
fn remove_close(fd: i32) -> Result<(), SimulatorError> {
let mut flags = FdFlag::from_bits_truncate(fcntl::fcntl(fd, FcntlArg::F_GETFD).unwrap());
flags.remove(FdFlag::FD_CLOEXEC);
fcntl::fcntl(fd, FcntlArg::F_SETFD(flags))
.map_err(|e| SimulatorError::FifoCreationError(format!("{e}")))?;
Ok(())
}
fn setup_pipe(f: &str) -> Result<(File, File), SimulatorError> {
Fifo::open_fifo(f)?;
let stdin = OpenOptions::new()
.custom_flags(O_NONBLOCK)
.read(true)
.open(f)
.map_err(|e| SimulatorError::FifoCreationError(format!("{e}")))?;
let stdout = OpenOptions::new()
.write(true)
.open(f)
.map_err(|e| SimulatorError::FifoCreationError(format!("{e}")))?;
let stdin_fd = stdin.as_raw_fd();
let stdout_fd = stdout.as_raw_fd();
Fifo::make_blocking(stdin_fd)?;
Fifo::remove_close(stdin_fd)?;
Fifo::remove_close(stdout_fd)?;
Ok((stdin, stdout))
}
pub fn new(filename: String) -> Result<Self, SimulatorError> {
let (fin, fout) = Fifo::setup_pipe(&filename)?;
Ok(Self {
_name: filename,
_in: Some(fin),
_out: Some(fout),
})
}
pub fn get_ends(&mut self) -> Option<(File, File)> {
match (self._in.take(), self._out.take()) {
(Some(_in), Some(_out)) => Some((_in, _out)),
_ => None,
}
}
}
impl Drop for Fifo {
fn drop(&mut self) {
let _ = remove_file(&self._name);
}
}
#[cfg(test)]
mod fifo_tests {
use std::{
io::{Read, Write},
process::{Command, Stdio},
};
use super::*;
#[test]
fn communication_test() {
let mut fifo = Fifo::new("/tmp/p1".to_owned()).unwrap();
let (mut fin, mut fout) = fifo.get_ends().unwrap();
let s1 = fout.write(b"Hello World").unwrap();
fout.flush().unwrap();
let mut buffer = vec![0; s1];
let s2 = fin.read(&mut buffer).unwrap();
let string = String::from_utf8(buffer).unwrap();
assert_eq!(s1, s2);
assert_eq!(string, "Hello World".to_owned());
log::info!("{string}");
}
#[test]
fn added_data_to_fifo_before_running_cmd_is_saved() {
let mut fifo = Fifo::new("/tmp/p1".to_owned()).unwrap();
let (fin, mut fout) = fifo.get_ends().unwrap();
let _ = fout.write(b"Hello World").unwrap();
fout.flush().unwrap();
drop(fout); // will send eof to the read end
{
let python_code = "import sys\nsys.stdout.write(sys.stdin.readline())";
let mut temp_python_file = File::create("temp_py.py").unwrap();
temp_python_file.write_all(python_code.as_bytes()).unwrap();
}
match Command::new("python3")
.args(["temp_py.py"])
.stdout(Stdio::piped())
.stdin(fin)
.spawn()
.unwrap()
.wait_with_output()
{
Ok(out) => {
assert_eq!("Hello World", String::from_utf8(out.stdout).unwrap().trim());
}
Err(_) => {
panic!();
}
}
let _ = remove_file("temp_py.py");
}
#[test]
fn get_ends() {
let fifo = Fifo::new("/tmp/p2".to_owned());
assert!(fifo.is_ok());
let mut fifo = fifo.unwrap();
assert!(fifo.get_ends().is_some());
assert!(fifo.get_ends().is_none());
}
}