You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The POSIX standard defines the ctermid C function to get the file path of the process controlling terminal. All Unix-like OSes are mostly POSIX compliant, so this function can be assumed to be available on every Unix-like target.
Therefore, this crate could be refactored to just be a nice, safe facade to that C function, to save quite a bit of complexity with build scripts and be even more cross-platform than it currently is.
For a project of mine, I've came up with the following function that you can use as you like:
/// Returns a file path to the controlling terminal of this process. If this/// process has no controlling terminal or an error happens, `None` will/// be returned.fnctermid() -> Option<String>{use std::ffi::CString;use std::os::raw::{c_char, c_uchar};extern"C"{/// `char* ctermid(char* s)`, from `#include <stdio.h>`.////// Documentation: <https://pubs.opengroup.org/onlinepubs/9699919799/functions/ctermid.html>fnctermid(s:*mutc_char) -> *mutc_char;}// SAFETY: system calls are unsafe. ctermid is required by the standard to populate the passed// pointer with a valid string, always. If some error happens, then the string is empty, but the// pointer is valid. Because we bring our own buffer, safe Rust is in full control of the data// lifetime. L_ctermid is 9 on Linux, but allocating space for 256 characters should guarantee// that the buffer size is always greater than L_ctermid. c_uchar has the same memory layout// than c_char and are interchangeable#[allow(unsafe_code)]let path = unsafe{letmut path_buf = vec![0as c_uchar; 256];ctermid(path_buf.as_mut_ptr()as*mutc_char);// CString requires that the Vec exactly contains a C string, with no NUL bytesletmut found_nul = false;
path_buf.retain(|byte| {let is_not_first_nul = *byte != 0 && !found_nul;
found_nul = found_nul || *byte == 0;
is_not_first_nul
});CString::new(path_buf)};
path.ok().and_then(|path_cstring| path_cstring.into_string().ok()).filter(|path| !path.is_empty())}
Thank you for making this useful library, by the way!
The text was updated successfully, but these errors were encountered:
The POSIX standard defines the
ctermid
C function to get the file path of the process controlling terminal. All Unix-like OSes are mostly POSIX compliant, so this function can be assumed to be available on every Unix-like target.Therefore, this crate could be refactored to just be a nice, safe facade to that C function, to save quite a bit of complexity with build scripts and be even more cross-platform than it currently is.
For a project of mine, I've came up with the following function that you can use as you like:
Thank you for making this useful library, by the way!
The text was updated successfully, but these errors were encountered: