Servidores

ulimit -n: límite blando y duro de ficheros abiertos, qué pasa al llegar (EMFILE), herencia a los hijos y comprobarlo en /proc/PID/limits (prueba)

Publicado el 2 de diciembre de 2026Última revisión: 2 de diciembre de 20269 min de lectura

Resultado de la prueba

con bash 5.2.21 y Python 3.12.3 como uid 10002, un bucle de Python con el límite blando en 50 abrió 47 ficheros y falló con errno EMFILE (24, Too many open files), código de salida 7 y 47 ficheros creados; un bucle de bash con límite 20 abrió 10 descriptores extra antes de fallar con 'cannot duplicate fd: Too many open files'. Un ulimit -Sn 33 dentro de un subshell no cambió el padre (siguió en 524288/524288). ulimit -n 40 fijó blando y duro a 40. Bajar el límite duro por debajo del blando falló con Invalid argument y no cambió nada; bajando primero el blando (50) y luego el duro (60) funcionó; subir el duro a 100 falló con Operation not permitted y el duro siguió en 60; subir el blando a 55 funcionó y a 70 (por encima del duro) falló. El blando pudo volver al duro. Los hijos de bash y de Python heredaron blando=123 y duro=456, y un hijo que bajó su propio blando a 10 no cambió el del padre (123). /proc/PID/limits mostró soft=77 hard=88 para un sleep lanzado con esos límites y un proceso iniciado antes de un ulimit conservó 524288 mientras el iniciado después tuvo 99. No se probó como root, ni limits.conf/PAM, ni LimitNOFILE de systemd, ni /proc/sys/fs/file-max, ni fd de sockets. Mismos resultados en 3 de 3 ejecuciones.

Contenido

Este artículo no contiene enlaces de afiliado.

"Too many open files" es uno de los errores que más cuesta relacionar con su causa, porque el proceso falla lejos del sitio donde se agota el límite. Aquí se mide con ulimit -n qué ocurre exactamente: cuántos descriptores se pueden abrir, cómo falla un programa, qué hereda un proceso hijo, qué se puede y qué no se puede cambiar sin ser root, y cómo ver el límite de un proceso que ya está en marcha. Si lo que buscas es quién tiene abiertos ficheros concretos, mira archivo borrado que sigue ocupando disco, que usa también /proc/PID/fd. Para otro caso en que un proceso conserva un descriptor, está logrotate: copytruncate, rename y postrotate.

Condiciones: Ubuntu 24.04.5 LTS, Linux 7.0.0-1017-oracle, bash 5.2.21, Python 3.12.3, usuario normal (uid 10002), sin sudo, en directorios de mktemp -d que el script borra al salir; solo se detienen procesos que lanza el propio script. Los límites de partida del contenedor eran 524288 (blando y duro). El script se ejecutó 3 veces y la salida fue idéntica en las 3. No se probó ejecutar como root (que sí puede subir el límite duro), /etc/security/limits.conf ni PAM, LimitNOFILE de systemd, el límite global fs.file-max ni fs.nr_open, otros intérpretes (zsh, dash), sockets o tuberías como causa del agotamiento (solo ficheros normales y redirecciones de bash), ni el comportamiento de ningún servicio real. El texto lo redacté con ayuda de una IA a partir de la salida del script, y las cifras salen de esas ejecuciones.

Salida de la ejecución 1

Idéntica en las ejecuciones 2 y 3.

Ubuntu 24.04.5 LTS; Linux 7.0.0-1017-oracle; bash 5.2.21; Python 3.12.3; uid=10002
[1] initial limits seen by the script: soft<=hard: yes
[2] python loop with soft limit 50 (inside subshell):
  opened=47 errno=EMFILE (24) msg=Too many open files
  exit code=7
  files really created: 47
[3] bash loop with soft limit 20, extra fds opened with exec:
  extra fds opened=10; failure message: redirection error: cannot duplicate fd: Too many open files
[4] subshell does not affect parent:
  parent before: soft=524288 hard=524288
  subshell sets -Sn 33: soft=33
  parent after: soft=524288 hard=524288
[5] ulimit -n without -S/-H:
  ulimit -n 40 sets: soft=40 hard=40
[6] cannot raise hard limit after lowering:
  hard below the current soft: ulimit: open files: cannot modify limit: Invalid argument
  after -Hn 60 with soft above it: soft=524288 hard=524288
  after -Sn 50 then -Hn 60: soft=50 hard=60
  raise hard to 100: ulimit: open files: cannot modify limit: Operation not permitted
  hard now=60
  exit code of raise=1
  soft to 55 (below hard): ok soft=55
  soft to 70 (above hard): ulimit: open files: cannot modify limit: Invalid argument
[7] soft can go back up to hard:
  soft restored to hard: yes
[8] child inherits limits:
  bash child: soft=123 hard=456
  python child: soft=123 hard=456
  parent after a child lowered its own soft to 10: soft=123
[9] /proc/PID/limits of a running process:
  /proc/PID/limits: soft=77 hard=88 units=files
  open fds of that process: 3
  this script: soft=524288 hard=524288; equals ulimit -Sn: yes
[10] limit set after a process started:
  started before ulimit: soft=524288
  started after ulimit:  soft=99

Lo que se ve

Qué significa

Para un servicio que da "Too many open files", mirar ulimit -n en tu sesión no sirve: hay que mirar /proc/PID/limits del proceso, porque su límite lo decidió quien lo lanzó. Cambiar el límite después no afecta a procesos ya en marcha (en este test, el iniciado antes siguió en 524288), así que hay que reiniciarlo. Y como el duro no se puede subir sin privilegios, un script que lo baja "para probar" deja esa sesión limitada hasta que se cierre; usar un subshell evita ese efecto. Cómo se fija el límite de un servicio de systemd o de un usuario con PAM no se midió aquí.

Script completo

#!/bin/bash
# ulimit -n (open files): soft vs hard, EMFILE at the limit, inheritance, no raising the hard limit, subshell, /proc/PID/limits.
# Runs as a normal user in a mktemp dir (removed on exit); only kills processes it started.
# Usage: test-ulimit-n-emfile.sh   (needs bash and python3)
set -u
export LC_ALL=C.UTF-8
T=$(mktemp -d /tmp/ulimit.XXXXXX) || exit 1
P=
trap '[ -n "$P" ] && kill $P 2>/dev/null; wait 2>/dev/null; rm -rf "$T"' EXIT
echo "$(. /etc/os-release; echo "$PRETTY_NAME"); $(uname -sr); bash ${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}.${BASH_VERSINFO[2]}; $(python3 -V); uid=$(id -u)"
OPEN='import sys,os,errno
d=sys.argv[1]; n=0; fs=[]
try:
    while True:
        fs.append(open(os.path.join(d,"f%d"%n),"w")); n+=1
except OSError as e:
    print("opened=%d errno=%s (%s) msg=%s"%(n,errno.errorcode[e.errno],e.errno,os.strerror(e.errno)))
    sys.exit(7)'
SH0=$(ulimit -Sn); HH0=$(ulimit -Hn)
for r in 1 2 3; do
echo "=== run $r ==="
echo "[1] initial limits seen by the script: soft<=hard: $([ "$HH0" = unlimited ] || [ "$SH0" -le "$HH0" ] && echo yes || echo no)"
echo "[2] python loop with soft limit 50 (inside subshell):"
rm -rf "$T/a"; mkdir -p "$T/a"
( ulimit -Sn 50; python3 -c "$OPEN" "$T/a"; echo "exit code=$?" ) 2>&1 | sed 's/^/  /'
echo "  files really created: $(ls "$T/a" | wc -l)"
echo "[3] bash loop with soft limit 20, extra fds opened with exec:"
( ulimit -Sn 20; n=0
  while [ $n -lt 100 ]; do
    exec {fd}< "$T/a/f0" 2>/dev/null || break
    n=$((n+1))
  done
  echo "  extra fds opened=$n; failure message: $( { exec {fd}< "$T/a/f0"; } 2>&1 | sed "s#$T#TMP#; s#^[^:]*: line [0-9]*: ##; s#^[^:]*: ##" | head -1 )" )
echo "[4] subshell does not affect parent:"
echo "  parent before: soft=$(ulimit -Sn) hard=$(ulimit -Hn)"
echo "  subshell sets -Sn 33: soft=$( ( ulimit -Sn 33; ulimit -Sn ) )"
echo "  parent after: soft=$(ulimit -Sn) hard=$(ulimit -Hn)"
echo "[5] ulimit -n without -S/-H:"
echo "  ulimit -n 40 sets: $( ( ulimit -n 40; echo "soft=$(ulimit -Sn) hard=$(ulimit -Hn)" ) )"
echo "[6] cannot raise hard limit after lowering:"
( ulimit -Hn 60 2>&1 | sed 's/^[^:]*: line [0-9]*: /  hard below the current soft: /'
  echo "  after -Hn 60 with soft above it: soft=$(ulimit -Sn) hard=$(ulimit -Hn)"
  ulimit -Sn 50; ulimit -Hn 60; echo "  after -Sn 50 then -Hn 60: soft=$(ulimit -Sn) hard=$(ulimit -Hn)"
  ulimit -Hn 100 2>&1 | sed 's/^[^:]*: line [0-9]*: /  raise hard to 100: /'; echo "  hard now=$(ulimit -Hn)"
  ulimit -Hn 100 2>/dev/null; echo "  exit code of raise=$?"
  ulimit -Sn 55 && echo "  soft to 55 (below hard): ok soft=$(ulimit -Sn)"
  ulimit -Sn 70 2>&1 | sed 's/^[^:]*: line [0-9]*: /  soft to 70 (above hard): /' )
echo "[7] soft can go back up to hard:"
( ulimit -Sn 10; ulimit -Sn "$(ulimit -Hn)"; echo "  soft restored to hard: $([ "$(ulimit -Sn)" = "$(ulimit -Hn)" ] && echo yes || echo no)" )
echo "[8] child inherits limits:"
( ulimit -Sn 123; ulimit -Hn 456
  echo "  bash child: $(bash -c 'echo soft=$(ulimit -Sn) hard=$(ulimit -Hn)')"
  echo "  python child: $(python3 -c 'import resource;print("soft=%d hard=%d"%resource.getrlimit(resource.RLIMIT_NOFILE))')"
  bash -c 'ulimit -Sn 10'; echo "  parent after a child lowered its own soft to 10: soft=$(ulimit -Sn)" )
echo "[9] /proc/PID/limits of a running process:"
( ulimit -Sn 77; ulimit -Hn 88; exec sleep 30 ) & P=$!
sleep 0.5
echo "  /proc/PID/limits: $(awk '/Max open files/{print "soft="$4" hard="$5" units="$6}' /proc/$P/limits)"
echo "  open fds of that process: $(ls /proc/$P/fd | wc -l)"
kill $P 2>/dev/null; wait $P 2>/dev/null; P=
echo "  this script: $(awk '/Max open files/{print "soft="$4" hard="$5}' /proc/$$/limits); equals ulimit -Sn: $([ "$(awk '/Max open files/{print $4}' /proc/$$/limits)" = "$(ulimit -Sn)" ] && echo yes || echo no)"
echo "[10] limit set after a process started:"
( sleep 30 & A=$!; ulimit -Sn 99; sleep 30 & B=$!; sleep 0.3
  echo "  started before ulimit: $(awk '/Max open files/{print "soft="$4}' /proc/$A/limits)"
  echo "  started after ulimit:  $(awk '/Max open files/{print "soft="$4}' /proc/$B/limits)"
  kill $A $B; wait 2>/dev/null )
done

Este artículo no contiene enlaces de afiliado.