Debian Codegraph @

debian/rust-vendor/rlimit/examples/sys_limits.rs

raw
1 //! Example demonstrating how to read system-wide file descriptor limits.
2 //!
3 //! This example shows the difference between:
4 //! - System-wide limits from /proc/sys/fs/
5 //! - Per-process limits from getrlimit()
6 //!
7 //! Run with: cargo run --example sys_limits
8
9 #[cfg(any(target_os = "linux", target_os = "android"))]
10 fn main() {
11 use rlimit::{Resource, SysLimits};
12
13 println!("=== System-wide File Descriptor Limits ===\n");
14
15 // Read system-wide limits
16 match SysLimits::read() {
17 Ok(limits) => {
18 if let Some(file_max) = limits.file_max {
19 println!("System file-max: {}", file_max);
20 println!(" (Maximum number of file descriptors system-wide)");
21 }
22
23 if let Some(file_nr) = &limits.file_nr {
24 println!("\nCurrent file descriptor usage:");
25 println!(" Allocated: {}", file_nr.allocated);
26 println!(" Free: {}", file_nr.free);
27 println!(" Maximum: {}", file_nr.maximum);
28
29 let usage_percent = if file_nr.maximum > 0 {
30 (file_nr.allocated as f64 / file_nr.maximum as f64) * 100.0
31 } else {
32 0.0
33 };
34 println!(" Usage: {:.2}%", usage_percent);
35 }
36
37 if let Some(nr_open) = limits.nr_open {
38 println!("\nPer-process nr_open: {}", nr_open);
39 println!(" (Maximum NOFILE limit that can be set per-process)");
40 }
41 }
42 Err(e) => {
43 eprintln!("Failed to read system limits: {}", e);
44 return;
45 }
46 }
47
48 println!("\n=== Per-process NOFILE Limit ===\n");
49
50 // Compare with per-process NOFILE limit
51 match Resource::NOFILE.get() {
52 Ok((soft, hard)) => {
53 println!("NOFILE soft limit: {}", soft);
54 println!("NOFILE hard limit: {}", hard);
55 println!(" (Limits for this process only)");
56 }
57 Err(e) => {
58 eprintln!("Failed to get NOFILE limit: {}", e);
59 }
60 }
61
62 println!("\n=== Key Differences ===\n");
63 println!("• file-max: System-wide limit on total file descriptors");
64 println!("• nr_open: Maximum value for per-process NOFILE limit");
65 println!("• NOFILE: Actual limit for this specific process");
66 println!();
67 println!("Hierarchy: file-max >= sum(all process NOFILE) and NOFILE <= nr_open");
68 }
69
70 #[cfg(not(any(target_os = "linux", target_os = "android")))]
71 fn main() {
72 println!("This example only works on Linux and Android systems.");
73 println!("System-wide limits are not available on this platform.");
74 }