On Sun, Feb 02, 2020 at 11:37:12PM +0000, Laurence Tratt wrote:

> While writing a daemon in Rust, I discovered that, AFAICT, one doesn't have
> sensible access to __progname and has to figure out the executable name
> dynamically (AFAICT), so it ends up in malloc'd storage.
>

You probably should use getprogname(3) directly or via libc
crate. Apparently getprogname(3) is just "return __progname":

  https://github.com/openbsd/src/blob/master/lib/libc/gen/getprogname.c

getprogname(3) is supported at least in OpenBSD, NetBSD, FreeBSD,
DragonBSD, macOS and Apple iOS.

So something like this should work. There's also some gymnastics from
null terminated string to Rust string but as long as you keep it as
CStr no allocation should occur.


use std::ffi::CStr;
use std::os::raw::c_char;

extern "C" {
    pub fn getprogname() -> *const c_char;
}

fn main() {
    let progname = unsafe { 
        let ptr = getprogname();
        CStr::from_ptr(ptr)
    };

    // Lossy conversion to UTF-8 string so we can print it out stdout
    let name = progname.to_string_lossy();
    println!("progname: {}", name);
}


-- 
Ossi Herrala

Reply via email to