Ulimit -a, 'open files'

Without running ulimit -a and running grep, is there a less hacky way to get the # of allowed open files ?

Context: playing with toy bit cask impl in Rust, need to figure out allowed # of open files

Without going into OS hacking territory, I don't think you can raise the limit without raising the limit ?

Edit: I didn't read your question right, you can read those files directly to get the information you want.

1 Like

To determine the number, I think you want to use RLIMIT_NOFILE with getrlimit() (or getrlimit64). I don't know if there are any safe bindings, but it's available from the libc crate.

Edit: This library looks more ergonomic: rlimit - Rust

1 Like

Bash's implementation of ulimit -n calls getdtablesize():

fn open_file_limit() -> usize {
    unsafe { libc::getdtablesize() }.try_into().unwrap()
}

And glibc's implementation of getdtablesize calls getrlimit(RLIMIT_NOFILE, ...):

fn open_file_limit() -> usize {
    use libc::{getrlimit, rlimit, RLIMIT_NOFILE};
    let mut rlim = rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    let result = unsafe { getrlimit(RLIMIT_NOFILE, &mut rlim) };
    assert!(result == 0);
    rlim.rlim_cur.try_into().unwrap()
}

// or:

fn open_file_limit() -> usize {
    use nix::sys::resource::{getrlimit, Resource};
    let rlim = getrlimit(Resource::RLIMIT_NOFILE).unwrap();
    rlim.0.unwrap().try_into().unwrap()
}

Either the nix version or the rlimit crate mentioned above should work for your case.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.