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
155
156
157
158
159
160
161
use crate::Close;
use libc::c_int;
use std::fmt::Display;

pub enum PipeSide {
    Read,
    Write,
}

// the other side of the pipe need to closed when you need to use one side, or one process will be suspend
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Pipe {
    fd: (c_int, c_int),
}

impl Pipe {
    pub fn new(&fds: &[libc::c_int; 2]) -> Pipe {
        Pipe {
            fd: (fds[0], fds[1]),
        }
    }
    pub fn pipe() -> Option<Pipe> {
        let mut end = [0; 2];
        match unsafe { libc::pipe(end.as_mut_ptr()) } {
            libc::INT_MIN..=-1 => None,
            _ => Some(Pipe::new(&end)),
        }
    }

    pub fn pipe2(flag: i32) -> Option<Pipe> {
        let mut end = [0; 2];
        match unsafe { libc::pipe2(end.as_mut_ptr(), flag) } {
            libc::INT_MIN..=-1 => None,
            _ => Some(Pipe::new(&end)),
        }
    }

    pub fn get(&self, side: PipeSide) -> c_int {
        match side {
            PipeSide::Read => self.fd.1,
            PipeSide::Write => self.fd.0,
        }
    }
}

impl Drop for Pipe {
    fn drop(&mut self) {
        match Close::close(&[self.fd.0, self.fd.1]) {
            Ok(_) => (),
            Err(v) => eprintln!("{}", v),
        }
    }
}

impl Display for Pipe {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(
            std::format!(
                "pipe: | for_read(fd[0]) {} <<= for_write(fd[1]) {} |",
                self.fd.0,
                self.fd.1,
            )
            .as_str(),
        )
    }
}
#[macro_export]
macro_rules! create_pipe {
    (1) => {{
        let mut pipe = [libc::c_int; 2];
        match unsafe {
            pipe(pipe.as_mut_ptr())
        } {
            -1 => None,
            _  => Some(pipe)
        }
    }};
    ($n: expr) => {{
        if $n <= 0 {
            None
        } else {
            let mut pipes: [[libc::c_int; 2]; $n] = [[0; 2]; $n];
            let mut success = true;
            for i in 0..$n as usize {
                unsafe {
                    match libc::pipe(pipes[i].as_mut_ptr()) {
                        0 => {}
                        _ => {
                            success = false;
                            break;
                        }
                    }
                };
            }
            if success {
                Some(pipes)
            } else {
                None
            }
        }
    }};
}

#[macro_export]
macro_rules! create_pipe2 {
    ($n: expr, $modes: expr) => {{
        if $n != $modes.len() || $n == 0 {
            None
        } else {
            let mut pipes: [[libc::c_int; 2]; $n] = [[0; 2]; $n];
            let mut success = true;
            for i in 0..$n as usize {
                unsafe {
                    match libc::pipe2(pipes[i].as_mut_ptr(), $modes[i]) {
                        0 => {}
                        _ => {
                            success = false;
                            break;
                        }
                    }
                };
            }
            if success {
                Some(pipes)
            } else {
                None
            }
        }
    }};
}

#[cfg(test)]
mod pipe {
    use std::{error::Error, ffi::CString};

    use libc::execl;

    use crate::Close;

    #[test]
    fn test_execl() -> Result<(), Box<dyn Error>> {
        let path = CString::new("/bin/sh")?;
        let sh = CString::new("sh")?;
        let exec = CString::new("-c")?;
        let arg = CString::new("ls")?;
        // unsafe { execl(path.as_ptr(), sh.as_ptr(), exec.as_ptr(), arg.as_ptr(), 0) };
        Ok(())
    }

    #[test]
    fn test_create_pipe_macro() {
        let pipes1 = create_pipe!(1 + 1).unwrap();
        let pipes2 = create_pipe!(1 & 1).unwrap();
        assert!(pipes1.len() == 2);
        assert!(pipes2.len() == 1);
        let s = &pipes1.iter().flatten().map(|x| *x).collect::<Vec<i32>>()[..];
        Close::close(s).unwrap();
        let s1 = &pipes2.iter().flatten().map(|x| *x).collect::<Vec<i32>>()[..];
        Close::close(s1).unwrap();
    }
}