PREP WITH PROOF
Menu
LINUX & TROUBLESHOOTING / PRACTICAL GUIDE

Linux Too Many Open Files: Diagnose EMFILE and File Limits

Diagnose Linux EMFILE versus ENFILE, inspect the failing process, trace descriptor growth and verify a durable fix. Includes a bounded Python reproduction lab.

THE QUICK ANSWER

Start with the failing operation, its error code and the actual process ID. EMFILE points to a process descriptor limit; ENFILE points to the system-wide open-file limit. Inspect the running process before changing its launcher configuration, and distinguish legitimate concurrency from descriptors that are never released.

A file error can be a socket problem

A web worker stops accepting connections. A batch job cannot open its next input. Logging fails immediately afterward. All three symptoms can arise when a process cannot obtain another file descriptor. The filename in the last log message may identify the first operation that noticed exhaustion, rather than the resource that consumed the budget.

File descriptors also represent sockets, pipes and kernel event interfaces. Investigating only ordinary files can therefore miss the cause. Preserve the earliest error, the time, the process identity and the workload level. A restart may restore service, but it also discards useful evidence about the exhausted process.

This guide includes a standalone Linux lab tested locally with Python 3.12.14. It lowers only its own soft limit, opens a bounded number of descriptors to /dev/null, observes EMFILE and closes them. The systemd deployment example is reference-reviewed; it was not applied to a running service.

Separate EMFILE from ENFILE before choosing a fix

For open(), Linux distinguishes EMFILE, the per-process descriptor limit, from ENFILE, the system-wide open-file limit. Capture the errno or structured exception where possible. A wrapper may translate both into similar text, so the English message alone can be insufficient.

RLIMIT_NOFILE bounds descriptor numbers: it is one greater than the largest descriptor number the process can open. Its soft value is the enforced limit; the hard value constrains how far an unprivileged process can raise the soft value. This distinction matters when configuration tools display two different numbers.

An EMFILE investigation belongs first to the affected process and its launcher. An ENFILE investigation needs host-wide evidence. Changing fs.file-max does not automatically raise a worker’s RLIMIT_NOFILE, and increasing one worker’s limit does not repair system-wide exhaustion. Treat unexpected errors such as EACCES or ENOSPC as separate diagnostic branches.

Observed evidenceFirst questionAvoid this shortcut
EMFILE from the workerWhich process limit and descriptors are involved?Changing a host sysctl first
ENFILE from open()Is the host open-file table exhausted?Increasing only the worker limit
One healthy shell has a high ulimitWhat did the failing process actually inherit?Assuming the shell represents the service

Source: Linux open(2): EMFILE and ENFILE errors ↗

Inspect the worker, not your login shell

A shell’s ulimit describes that shell and the children it subsequently launches. An already running daemon may have been started by a different manager with different settings. A master process and its workers may also need separate inspection. Record the actual failing worker PID and confirm that it still refers to the intended process.

The following commands are read-only. Replace 1234 with the confirmed PID; prlimit displays values because no replacement limit is supplied. The proc file exposes both soft and hard limits. A missing process, permission failure or inaccessible proc mount is an unavailable observation, not evidence that usage is zero.

For a service that restarts automatically, associate each sample with its PID and collection time. A newly created worker is not a continuation of the previous worker’s descriptor history. In containers, collect evidence in the appropriate PID namespace or map the worker to its host PID deliberately. The PID must also match the mounted proc filesystem; a host-mounted proc tree can expose different numbers from those returned inside a container.

pid=1234  # Replace with the confirmed failing worker PID.
cat "/proc/$pid/limits"
prlimit --pid "$pid" --nofile
# This describes the current Bash shell, not the worker:
ulimit -Sn
ulimit -Hn

Source: Linux getrlimit(2): RLIMIT_NOFILE and soft/hard limits ↗

Count descriptors and inspect what they represent

On Linux, /proc/PID/fd has numbered entries for open descriptors. Targets can identify regular paths, sockets, pipes and anonymous kernel interfaces. Use a count to track direction, then inspect representative targets to explain the growth. A count without a resource category rarely tells you which code path needs attention.

This Python snippet reports numbered entries and the highest observed descriptor number without opening their targets. The directory listing is a moving snapshot, so it is not an atomic inventory of a busy process. It deliberately reports failures instead of converting them to a misleading zero.

Inspect selected entries with readlink or use lsof -nP -p PID when installed. Restrict access to collected paths and connection details. A socket inode is an identifier, not proof of a leak, and one file path can have several descriptors. Compare observations during comparable workload phases rather than treating every duplicate path as a defect.

pid=1234
python3 - "$pid" <<'PYCODE'
import os
import sys

raw = sys.argv[1]
if not raw.isascii() or not raw.isdecimal() or int(raw) <= 0:
    raise SystemExit('Use a positive numeric PID.')
try:
    with os.scandir(f'/proc/{int(raw)}/fd') as entries:
        numbers = [int(e.name) for e in entries if e.name.isdecimal()]
except OSError as exc:
    raise SystemExit(f'Descriptor snapshot unavailable: {exc}')
print('Observed descriptor entries:', len(numbers))
print('Highest observed descriptor:', max(numbers, default=None))
PYCODE

Source: Linux proc_pid_fd(5): descriptor entries and targets ↗

Tell a bounded pool from a resource leak

Collect a short series under steady load, after load stops, and during a repeated workload cycle. A connection pool that fills and stabilizes can be expected behavior. A growing baseline after each completed cycle is stronger evidence that resources are being retained, although it still does not identify the responsible owner.

Correlate descriptor growth with active requests, worker concurrency, upstream connection counts and application shutdown events. If usage scales with active work and falls afterward, the budget may be too small for the intended concurrency. If it never falls, review ownership and cleanup before merely allowing a larger backlog.

Common review targets include unclosed response bodies, per-request clients instead of reused clients, files opened outside a cleanup scope, failed connection attempts, and pipes whose unused ends remain open. Inspect error and cancellation paths as carefully as successful requests. A timeout that abandons work without releasing its resources can turn a transient dependency failure into local exhaustion.

Reproduce EMFILE in a disposable process

Save the following as fd_lab.py and run python3 -B fd_lab.py as a standalone process on a Linux learning machine. It needs initial soft and hard limits of at least 16. It does not create disk files, change the hard limit, or alter the parent shell or system configuration.

The loop attempts at most 65 opens, using a soft ceiling no greater than either starting limit. It records the expected failure without trying to open diagnostic files while exhausted. Cleanup runs before the recovery check, which verifies that opening works again while the same low soft limit is still active.

The final step restores the original pair inside the lab process. The exact number of successful opens depends on descriptors inherited at startup; do not copy the locally observed count into a capacity policy. The important observations are EMFILE, successful cleanup and recovery at the unchanged low limit.

# Run as a standalone Python 3 process on Linux.
import errno
import os
import resource

original = resource.getrlimit(resource.RLIMIT_NOFILE)
soft, hard = original
ceiling = min([64] + [n for n in original if n != resource.RLIM_INFINITY])
if ceiling < 16:
    raise SystemExit('Lab needs soft and hard limits of at least 16.')

held = []
observed = None
resource.setrlimit(resource.RLIMIT_NOFILE, (ceiling, hard))
try:
    try:
        # Bounded: at most 65 attempts; no files are created.
        for _ in range(ceiling + 1):
            held.append(os.open(os.devnull, os.O_RDONLY))
    except OSError as exc:
        if exc.errno != errno.EMFILE:
            raise
        observed = exc.errno
    finally:
        opened = len(held)
        for fd in held:
            os.close(fd)
        held.clear()

    if observed != errno.EMFILE:
        raise RuntimeError('Expected EMFILE was not observed.')
    # Recovery is checked while the low soft limit is still in force.
    fd = os.open(os.devnull, os.O_RDONLY)
    os.close(fd)
    print(f'EMFILE observed; opened {opened} extra descriptors.')
    print('Opening works again after closing them, at the same low limit.')
finally:
    resource.setrlimit(resource.RLIMIT_NOFILE, original)

assert resource.getrlimit(resource.RLIMIT_NOFILE) == original
print('Original limits restored inside this process.')

Source: Python resource: getrlimit and setrlimit ↗

Fix resource ownership before selecting a larger limit

Give every opened resource a defined owner and lifetime. In Python, a with block is a useful default for ordinary files; asynchronous clients and streamed responses require their library’s own close or context-management contract. Closing a resource in one convenient success branch leaves all the other branches unresolved.

For a server, bound concurrency and pool sizes so downstream slowness cannot create unlimited live connections. Include listening sockets, inbound connections, outbound pools, logs, pipes and monitoring overhead in the estimate. A small multiplier based only on HTTP request count can miss long-lived streams or several upstream connections per request.

A higher limit can be justified when measured peak demand is legitimate and resource cleanup is correct. Select it with margin and host resource constraints in view, then validate under representative load. The lab proves a kernel error and a cleanup mechanism; it does not establish the correct limit for your application.

Make a justified change at the process launcher

For a systemd system service, LimitNOFILE belongs in the service execution configuration. A single value sets both limits; soft:hard sets them separately. The illustrative drop-in below is not a recommended default. Confirm that the application can handle descriptor numbers above 1023: Linux select() cannot handle them, so blindly raising the soft limit can expose a separate compatibility problem.

If a change is justified, preserve existing overrides, apply the narrow service drop-in, reload the manager configuration and schedule the service restart. Reloading the manager alone does not change the limits of an existing worker. Inspect the replacement worker’s /proc/PID/limits after restart; an application may adjust its own soft limit.

Per-user services and container launchers have their own inheritance and privilege constraints. A login-session limits file or an interactive ulimit change is not a universal daemon fix. Record the effective launcher settings and validate the process that actually serves traffic.

# Illustrative system-service drop-in; values require workload validation.
# /etc/systemd/system/example.service.d/limits.conf
[Service]
LimitNOFILE=4096:8192

Source: systemd.exec: LimitNOFILE execution settings ↗

If the evidence says ENFILE, inspect the host budget

Read /proc/sys/fs/file-nr and /proc/sys/fs/file-max on the affected host. file-nr reports allocated file handles, unused handles and the maximum. These are open-file descriptions, not a simple sum of every process’s descriptor count: duplicated or inherited descriptors can refer to the same description.

Also distinguish fs.nr_open, a ceiling on RLIMIT_NOFILE, from fs.file-max, the system-wide handle limit. Read these values as evidence before considering changes. Do not reproduce ENFILE by exhausting the host; that would affect unrelated workloads and is unnecessary for diagnosing a recorded incident.

Look for which workloads are growing and whether the host-wide observation aligns with the error time. Raising a ceiling without accounting for kernel memory, connection pressure and leaking processes can merely move the next failure elsewhere. A host-wide adjustment should have its own capacity review and recovery plan.

cat /proc/sys/fs/file-nr
cat /proc/sys/fs/file-max
cat /proc/sys/fs/nr_open

Source: Linux proc_sys_fs(5): file-nr, file-max and nr_open ↗

Verify recovery under the workload that triggered it

Confirm the intended worker identity and effective soft/hard limits after deployment. Repeat a representative workload while sampling descriptor counts and application failures. Success means the service completes its work and resource use returns to a defensible steady state, rather than merely surviving one request after restart.

Keep the before-and-after configuration, error codes, workload description and sample times together. Test cleanup when clients disconnect, upstreams time out and operations are cancelled. If you increased limits, check the host-wide picture too; several workers can each look healthy while collectively consuming a much larger budget.

The durable result is an explained resource lifecycle and a verified launch configuration. Use the error’s scope to choose the investigation, the running process to establish reality, and repeated workload evidence to decide whether a larger limit is necessary.

KEEP THESE THREE THINGS

Your next steps

  1. Capture errno and the actual failing PID before choosing between a per-process and host-wide investigation.
  2. Track descriptor categories and cleanup under repeated load; run the bounded lab only as a disposable process.
  3. After any justified launcher change, verify the new worker’s effective limits and steady-state resource use.

Sources & official resources

Linked resources checked on 2026-10-27. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →