How to get errno value from rust libc

Hello,

I have been trying to get errno value from the libc. For some reason, the API available in https://github.com/rust-lang/libc is not present. (using libc = "0.2")

Any clues how to get the errno value?

extern crate libc;

fn main() {
    println!("{}", *libc::___errno());
}

Fails compilation with the following output,

error[E0425]: cannot find function `___errno` in crate `libc`
 --> src/main.rs:4:27
  |
4 |     println!("{}", *libc::___errno());
  |                           ^^^^^^^^ not found in `libc`

Thanks

Seems like libc::__errno_location() is a better choice. But any better solution is welcome.

You might consider std::io::Error::last_os_error().raw_os_error().unwrap().

3 Likes

Thanks very much ! Does it panic if i make a call directly? I went ahead with __errno_location mostly because it doesn't panic.

io::Error::raw_os_error() is guaranteed to always return Some if you call it on the result of last_os_error():

Returns the OS error that this error represents (if any).

If this Error was constructed via last_os_error or from_raw_os_error, then this function will return Some, otherwise it will return None.

So the unwrap() there can never actually panic.

1 Like

Or you can write .unwrap_or(0) for a guaranteed-not-panicking unwrap, where 0 means "no error", since errno is guaranteed to be non-zero in case of error (NB: two links).

1 Like

Thanks. So far ok with libc::__errno_location. But curios as to why there are __ before errno_location. What does that signify?

It's there to say that you don't need to call it directly but have to use errno.h macro.

Not an option for Rust user, of course.

libc::__errno_location() is an internal platform-specific function that exists on the major Linux libc implementations. It does not necessarily exist on other Unix-like operating systems, nor on Windows. (For instance, the same function is instead called __errno() on OpenBSD and __error() on macOS.) The best cross-platform way to get the value of errno is to use io::Error::last_os_error(), which is guaranteed to return an io::Error representing an OS error.