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
extern crate nix;
#[cfg(any(target_os = "android", target_os = "linux"))]
pub use nix::pty::ptsname_r;
#[cfg(any(target_os = "macos", target_os = "ios"))]
use nix::pty::PtyMaster;
#[cfg(any(target_os = "macos", target_os = "ios"))]
use nix::Result;
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[inline]
pub fn ptsname_r(fd: &PtyMaster) -> Result<String> {
use nix::Error;
use nix::libc::{c_ulong, ioctl, TIOCPTYGNAME};
use std::os::unix::prelude::*;
use std::ffi::CStr;
let buf: [i8; 128] = [0; 128];
unsafe {
match ioctl(fd.as_raw_fd(), TIOCPTYGNAME as c_ulong, &buf) {
0 => {
let res = CStr::from_ptr(buf.as_ptr()).to_string_lossy().into_owned();
Ok(res)
}
_ => Err(Error::last()),
}
}
}
#[cfg(test)]
mod tests {
use nix::fcntl::OFlag;
use nix::pty::posix_openpt;
use std::os::unix::prelude::*;
use super::ptsname_r;
#[test]
#[cfg(any(target_os = "android", target_os = "linux", target_os = "macos", target_os = "ios"))]
fn test_ptsname_r_copy() {
let master_fd = posix_openpt(OFlag::O_RDWR).unwrap();
assert!(master_fd.as_raw_fd() > 0);
let slave_name1 = ptsname_r(&master_fd).unwrap();
let slave_name2 = ptsname_r(&master_fd).unwrap();
assert!(slave_name1 == slave_name2);
assert!(slave_name1.as_ptr() != slave_name2.as_ptr());
}
}