aboutsummaryrefslogtreecommitdiffstats
path: root/src/pty/async_io.rs
blob: 84097f9103e4cd38af601ab87c481c1f14940133 (plain) (blame)
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
use crate::error::*;

use std::os::unix::io::FromRawFd as _;

pub struct Pty {
    pt: std::fs::File,
    ptsname: std::path::PathBuf,
}

impl super::Pty for Pty {
    fn new() -> Result<Self> {
        let (pt_fd, ptsname) = super::create_pt()?;

        // safe because posix_openpt (or the previous functions operating on
        // the result) would have returned an Err (causing us to return early)
        // if the file descriptor was invalid. additionally, into_raw_fd gives
        // up ownership over the file descriptor, allowing the newly created
        // File object to take full ownership.
        let pt = unsafe { std::fs::File::from_raw_fd(pt_fd) };

        Ok(Self { pt, ptsname })
    }

    fn pt(&self) -> &std::fs::File {
        &self.pt
    }

    fn pts(&self) -> Result<std::fs::File> {
        let fh = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&self.ptsname)
            .map_err(|e| Error::OpenPts(self.ptsname.clone(), e))?;
        Ok(fh)
    }
}