Skip to content
systemcoding.dev
Systems Programming

Fix 'Too many open files' (EMFILE) by Raising RLIMIT_NOFILE

Fix the Too many open files error on Linux. Read RLIMIT_NOFILE, raise the soft limit in C, set systemd LimitNOFILE, and find the leak that caused it.

6 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the C, Linux and C++ logos.

The message arrives in a log or a terminal at the worst time:

Text
accept: Too many open files

or, from a program that opens a file, open: Too many open files. The system call failed with the error EMFILE, whose strerror() text is "Too many open files". It does not mean the machine ran out of anything. It means this one process reached the limit on how many descriptors it may hold at once, and the fix has two halves that people often swap: raise the limit if the program legitimately needs more, and find the leak if it should not. This post shows how to read the limit, raise it from the shell, from C and from a systemd unit, and how to tell which half applies. It assumes Linux 6.12 and a program that opens files or sockets with open(), socket() or accept().

What EMFILE and ENFILE mean

Two similar errors have different causes. EMFILE means the calling process has the maximum number of file descriptors open, a per-process limit called RLIMIT_NOFILE. ENFILE means the whole system has reached its limit on open files, set by the kernel parameter fs.file-max. The open(2) manual page lists both. The per-process limit is by far the common one: on many Linux distributions the soft default is 1024 descriptors, which a busy server reaches with a thousand connections.

RLIMIT_NOFILE has two values. The soft limit is what the kernel enforces. The hard limit is the ceiling to which an unprivileged process may raise its own soft limit. Only a privileged process may raise the hard limit. Remembering the two values is most of the fix, because "raise the limit" means "raise the soft limit up to the hard one" in almost every case.

Read the limit

From a shell, ulimit -n prints the soft limit and ulimit -Hn the hard limit:

Shell
ulimit -n
ulimit -Hn
Text
1024
524288

Those are example values. For a process that is already running, read /proc/<pid>/limits, which shows what that process actually has, regardless of what your shell says:

Shell
grep 'Max open files' /proc/$(pgrep -o app)/limits
Text
Max open files            1024                 524288               files

Reading the live process matters because a service started by a service manager gets its limit from the manager, not from your login shell. A common trap is raising the limit in your shell, restarting the service, and seeing no change.

Raise the soft limit from C

A program can raise its own soft limit to the hard limit at startup, which requires no privileges. The calls are getrlimit() and setrlimit() from <sys/resource.h>:

raise_nofile.cc
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>

int main(void)
{
    struct rlimit rl;

    if (getrlimit(RLIMIT_NOFILE, &rl) != 0) {
        perror("getrlimit");
        return EXIT_FAILURE;
    }
    printf("before: soft=%llu hard=%llu\n",
           (unsigned long long)rl.rlim_cur, (unsigned long long)rl.rlim_max);

    rl.rlim_cur = rl.rlim_max;               /* soft up to hard, no privilege needed */
    if (setrlimit(RLIMIT_NOFILE, &rl) != 0) {
        perror("setrlimit");
        return EXIT_FAILURE;
    }

    getrlimit(RLIMIT_NOFILE, &rl);
    printf("after:  soft=%llu hard=%llu\n",
           (unsigned long long)rl.rlim_cur, (unsigned long long)rl.rlim_max);
    return EXIT_SUCCESS;
}

Compiled with gcc -Wall -o raise_nofile raise_nofile.c on GCC 14, a run on a system with the example limits above prints:

Text
before: soft=1024 hard=524288
after:  soft=524288 hard=524288

The values are rlim_t, an unsigned type, so the code casts them for printf. Some systems report the hard limit as RLIM_INFINITY, which prints as a very large number, and requesting that as a soft limit can fail on Linux because the kernel caps it at fs.nr_open. If setrlimit() returns EPERM or EINVAL, ask for a finite value such as 65536 instead of the hard limit.

A server that expects heavy load can go one step further and derive the number it needs. Ten thousand client connections need about ten thousand descriptors plus a few dozen for logs, listeners and pipes, so setting the soft limit to a comfortable value and refusing to start when the kernel will not grant it is better than failing later under load.

Raise it for a service

A program started by systemd takes its limit from the unit. Add LimitNOFILE to the [Service] section:

app.serviceINI
[Service]
ExecStart=/usr/local/bin/app
LimitNOFILE=65536

After editing, run systemctl daemon-reload and restart the service, then verify with the /proc/<pid>/limits command above. For processes started from a login shell, /etc/security/limits.conf or a file in /etc/security/limits.d/ sets nofile for users through PAM, and it applies to sessions, not to services. In a container, the runtime sets the limit when the container starts, so raise it with the runtime's own option, such as the --ulimit nofile=65536:65536 flag of docker run.

Decide whether you have a leak

Raising the limit hides a leak without curing it. A process that opens a descriptor per request and never closes it will hit any finite limit, only later. The test is whether the count of open descriptors tracks the work in flight or only ever grows. Count the entries in the process's descriptor directory twice, a few minutes apart, under steady load:

Shell
ls /proc/$(pgrep -o app)/fd | wc -l
Text
1017

A number near the soft limit, still rising while traffic is flat, is a leak. Listing a process's open files shows how to group the targets to see what is accumulating. Typical findings are sockets never closed on an error path, a fopen() without fclose() in a function with an early return, and a child process holding the write end of a pipe because of a missing close-on-exec flag, which the O_CLOEXEC post covers.

The leak-proof pattern in C is to make every path out of a function close what the function opened. A single exit label keeps that readable:

no_leak.cc
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

int copy_header(const char *src, const char *dst)
{
    int in = -1, out = -1, rc = -1;
    char buf[512];

    in = open(src, O_RDONLY | O_CLOEXEC);
    if (in < 0)
        goto done;

    out = open(dst, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
    if (out < 0)
        goto done;

    ssize_t n = read(in, buf, sizeof buf);
    if (n < 0 || write(out, buf, (size_t)n) != n)
        goto done;
    rc = 0;

done:
    if (in >= 0)
        close(in);
    if (out >= 0)
        close(out);
    return rc;
}

Every goto done reaches both close() calls, so no early return can skip them. The initial -1 values make the cleanup safe when the first open() is the one that failed.

Handle EMFILE at runtime

A server should not die the moment accept() returns EMFILE. The listening socket stays readable while the queue holds a connection, so a loop that retries blindly spins at full CPU. A common remedy is to keep one spare descriptor, usually an open /dev/null, and on EMFILE close it, accept the pending connection, close that connection at once, and reopen the spare. The client gets a clean reset instead of waiting in the queue, and the accept loop makes progress.

The remedy limits damage during a spike. It does not replace a correct limit and a leak-free program, and for a service that should shed load, returning an error to clients earlier, before the descriptor count gets close to the limit, is the more graceful design.

When raising the limit is the wrong fix

If the count is near the limit because of a leak, raising it only delays the failure. If the limit is already large, there is another ceiling to consider: select() cannot watch descriptors numbered FD_SETSIZE or above, which is 1024 on Linux with glibc, so a program that uses select() can break at descriptor 1024 even with a higher RLIMIT_NOFILE. Moving to poll() or epoll removes that restriction. And for a system-wide ENFILE, adjust fs.file-max with sysctl, but first look for the process holding most of the files.

Also inDebugging
Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.