Skip to content

Instantly share code, notes, and snippets.

@miquels
Created February 5, 2019 14:40
Show Gist options
  • Save miquels/c47316f7b19a0af3d9927bafef94de35 to your computer and use it in GitHub Desktop.
Save miquels/c47316f7b19a0af3d9927bafef94de35 to your computer and use it in GitHub Desktop.
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <resolv.h>
#include <netdb.h>
void set_max_fds(int count) {
struct rlimit rlim;
getrlimit(RLIMIT_NOFILE, &rlim);
rlim.rlim_cur = count;
setrlimit(RLIMIT_NOFILE, &rlim);
}
void try_resolve(char *msg) {
struct addrinfo *res;
printf("%s: resolving localhost:1234: ", msg);
int r = getaddrinfo("localhost", "1234", NULL, &res);
if (r != 0) {
printf("%s\n", gai_strerror(r));
} else {
printf("ok\n");
}
}
int main() {
try_resolve("initial");
set_max_fds(3);
try_resolve("with too many fds open");
set_max_fds(128);
// uncomment this hack to make it work
// h_errno = 0;
try_resolve("with fds available again");
return 0;
}
use std::io;
use std::net::ToSocketAddrs;
use libc::{RLIMIT_NOFILE, getrlimit, rlimit, setrlimit};
fn set_max_fds(count: usize) -> io::Result<()> {
let mut rlim = rlimit{ rlim_cur: 0, rlim_max: 0 };
unsafe {
if getrlimit(RLIMIT_NOFILE, &mut rlim as *mut rlimit) != 0 {
return Err(io::Error::last_os_error());
}
rlim.rlim_cur = count as u64;
if setrlimit(RLIMIT_NOFILE, &rlim as *const rlimit) != 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
}
fn try_resolve(msg: &str) {
let addr = "localhost:1234";
println!("{}: resolving {}: {:?}", msg, addr, addr.to_socket_addrs());
}
fn main() -> Result<(), Box<std::error::Error>> {
try_resolve("initial");
set_max_fds(3)?;
try_resolve("with too many fds open");
set_max_fds(128)?;
// uncomment this hack to make it work
// extern { fn __h_errno_location() -> *mut i32; }
// unsafe { *__h_errno_location() = 0 }
try_resolve("with fds available again");
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment