use super::check;
use std::ffi::c_int;
use std::io;
pub(crate) fn open_pty() -> io::Result<(std::fs::File, std::fs::File)> {
use std::ffi::{CStr, c_char};
use std::os::fd::FromRawFd;
use std::os::unix::fs::OpenOptionsExt;
unsafe extern "C" {
fn posix_openpt(flags: c_int) -> c_int;
fn grantpt(fd: c_int) -> c_int;
fn unlockpt(fd: c_int) -> c_int;
fn ptsname(fd: c_int) -> *const c_char;
}
const O_RDWR: c_int = 2;
#[cfg(target_os = "linux")]
const O_NOCTTY: c_int = 0o400;
#[cfg(target_os = "macos")]
const O_NOCTTY: c_int = 0x2_0000;
#[cfg(target_os = "freebsd")]
const O_NOCTTY: c_int = 0x8000;
let fd = check(unsafe { posix_openpt(O_RDWR | O_NOCTTY) })?;
let master = unsafe { std::fs::File::from_raw_fd(fd) };
check(unsafe { grantpt(fd) }).map(drop)?;
check(unsafe { unlockpt(fd) }).map(drop)?;
let name = unsafe { ptsname(fd) };
if name.is_null() {
return Err(io::Error::last_os_error());
}
let path = unsafe { CStr::from_ptr(name) }
.to_string_lossy()
.into_owned();
let slave = std::fs::OpenOptions::new()
.read(true)
.write(true)
.custom_flags(O_NOCTTY)
.open(path)?;
Ok((master, slave))
}