Servidores

xargs -P y timeout: salida mezclada, códigos 123 a 127 y procesos nietos, medido con GNU xargs 4.9.0 y timeout 9.4

Publicado el 3 de diciembre de 2026Última revisión: 3 de diciembre de 202618 min de lectura

Resultado de la prueba

con 10 argumentos, `xargs` sin opciones lanzó 1 proceso, `-n3` lanzó 4 (3, 3, 3 y 1) y `-I{}` lanzó 10; con entrada vacía lanzó 1 proceso con 0 argumentos y con `-r` ninguno. Con `-P8` y una escritura por línea, las líneas de 100 y de 4000 caracteres por una tubería salieron enteras (8000 de 8000 y 4000 de 4000) y las de 200000 caracteres salieron mezcladas, con solo entre 19 y 57 líneas intactas de 160 (el mismo caso con redirección a fichero: 160 de 160). Si un hijo terminaba con 1, 2 o 100, xargs terminó con 123 y ejecutó los 10; con 255 terminó con 124 tras ejecutar solo 3; hijo muerto por señal 125, comando no ejecutable 126, no encontrado 127. `timeout 1 sleep 5` terminó con 124, con `-s KILL` con 137 y con `--preserve-status` con 143; con un hijo que ignora TERM, 124 sin `-k` y 137 con `-k 1`. Un `sleep` nieto en el mismo grupo murió con `timeout` por defecto y sobrevivió con `--foreground` y con `setsid`. Mismos resultados en 3 de 3 ejecuciones, salvo el número de líneas intactas del caso de 200000 caracteres. No se probó BSD xargs, busybox, otras versiones ni el uso de `timeout` con un terminal interactivo.

Contenido

Este artículo no contiene enlaces de afiliado.

xargs -P y timeout aparecen juntos en muchos scripts de cron y de copia: uno reparte el trabajo en paralelo y el otro pone un techo de tiempo. Aquí se mide qué hacen en la práctica en dos puntos que suelen darse por supuestos: la salida (cuántos procesos se lanzan y si las líneas de trabajos paralelos se mezclan) y los códigos de salida (qué devuelve xargs cuando un hijo falla, qué devuelve timeout según cómo acabe el comando y si mata a los procesos que el comando dejó detrás). Los nombres con espacios o saltos de línea con -print0 están en nombres de fichero con espacios y saltos de línea: xargs y -print0; la diferencia entre -exec ; y -exec + en find -exec, -delete y -prune; los códigos de salida de otra herramienta de cron, en flock -n y -w, y el ajuste de set -e en scripts, en set -e y set -euo pipefail en scripts de copia y cron.

Condiciones: Ubuntu 24.04.5 LTS, Linux 7.0.0-1017-oracle aarch64, GNU findutils 4.9.0 (xargs), GNU coreutils 9.4 (timeout), usuario normal sin privilegios. Todo ocurre en un directorio creado con mktemp -d en /tmp (el script comprueba que la ruta empieza por /tmp/xargsp. antes de nada y lo borra al terminar). Los "comandos" son scripts propios de sh y un escritor de python3 que hace una llamada write() por línea. El script se ejecutó 3 veces, las tres a la vez en la misma máquina, y la salida fue idéntica salvo la ruta temporal, el número aleatorio de los sleep y el número de líneas intactas del caso de 200000 caracteres, que fue 19, 22 y 57. Eso último depende de la carga del equipo y del reparto de la CPU: sirve para ver que se mezcla, no como cifra reproducible. No se probó BSD xargs, busybox ni otras versiones de GNU; ni xargs -P con más de 8 trabajos o con -P 0; ni otros tamaños de línea entre 4000 y 200000 caracteres, de modo que no se sabe dónde empieza a mezclarse; ni el uso de un terminal interactivo, que es donde se aplica --foreground en la práctica (aquí solo se midió si el nieto sobrevive); ni timeout dentro de systemd o de cron; ni contenedores. Tampoco se probó xargs -P con un fallo en medio de un lote mientras otros hijos siguen corriendo más allá de lo que muestra el recuento. 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

Las ejecuciones 2 y 3 salieron iguales, salvo lo indicado arriba.

xargs (GNU findutils) 4.9.0
timeout (GNU coreutils) 9.4
kernel: Linux 7.0.0-1017-oracle
[1] number of processes started by xargs on 10 arguments (args per process from the wrapper):
  xargs count                 -> 1 processes; args: 10
  xargs -n3 count             -> 4 processes; args: 3,3,3,1
  xargs -P4 -n3 count         -> 4 processes; args: 1,3,3,3
  xargs -I{} count {}         -> 10 processes; args: 1,1,1,1,1,1,1,1,1,1
  xargs -I{} -n3 count {}     -> xargs: warning: options --replace and --max-args/-n are mutually exclusive, ignoring previous --replace value
4 processes; args: 4,4,4,2
  xargs -I{} count {} {}      -> 10 processes; args: 2,2,2,2,2,2,2,2,2,2
  empty input, xargs count    -> 1 processes; args: 0
  empty input, xargs -r count -> 0 processes; args: 
[2] output interleaving, 8 jobs with xargs -P8 -I{}, one write() per line (lines pure = consist of one single letter):
  sink=pipe line=100 chars x 1000 lines per job: expected lines: 8000; lines in output: 8000; pure lines of the right length: 8000
  sink=pipe line=4000 chars x 500 lines per job: expected lines: 4000; lines in output: 4000; pure lines of the right length: 4000
  sink=pipe line=200000 chars x 20 lines per job: expected lines: 160; lines in output: 160; pure lines of the right length: 19
  sink=file line=200000 chars x 20 lines per job: expected lines: 160; lines in output: 160; pure lines of the right length: 160
[3] exit status of xargs when a child fails (10 args, -n1, failat3 returns the given status only for 3):
  child exits 1 -> xargs exit 123; children run: 10; stderr: 
  child exits 2 -> xargs exit 123; children run: 10; stderr: 
  child exits 100 -> xargs exit 123; children run: 10; stderr: 
  child exits 255 -> xargs exit 124; children run: 3; stderr: xargs: /tmp/xargsp.26K4PT/bin/failat3: exited with status 255; aborting 
  -P3, child exits 1 -> xargs exit 123; children run: 10
  child killed by SIGKILL -> xargs exit 125; stderr: xargs: sh: terminated by signal 9 
  child killed by SIGTERM -> xargs exit 125; stderr: xargs: sh: terminated by signal 15 
  command not executable (mode 644) -> xargs exit 126
  command not found -> xargs exit 127
  invalid option -> xargs exit 1
  argument list too long for one -s size -> xargs exit 1 (xargs: cannot fit single argument within argument list size limit)
  sh -c 'exit 0' -> xargs exit 0
  child exits 1, then the same with '|| true' wrapper in sh -c -> xargs exit 0
[4] timeout exit codes (limit 1 s):
  timeout 1 sleep 5 -> exit 124 (~1 s)
  timeout -s KILL 1 sleep 5 -> exit 137 (~1 s)
  timeout -s INT 1 sleep 5 -> exit 124 (~1 s)
  timeout --preserve-status 1 sleep 5 -> exit 143 (~1 s)
  timeout 1 sh -c 'trap "" TERM; sleep 5' -> exit 124 (~3 s)
  timeout -k 1 1 sh -c 'trap "" TERM; sleep 5' -> exit 137 (~2 s)
  timeout 5 sh -c 'exit 3' -> exit 3 (~0 s)
  timeout 5 sh -c 'exit 124' (child itself) -> exit 124 (~0 s)
  timeout 5 sh -c 'kill -9 $$' (child killed by itself) -> exit 137 (~0 s)
  timeout 5 nonexistent-cmd-xyz -> exit 127 (~0 s)
  timeout 5 notexec (mode 644) -> exit 126 (~0 s)
  timeout abc sleep 1 (invalid duration) -> exit 125 (~0 s)
  timeout --nonsense 1 sleep 1 -> exit 125 (~0 s)
  timeout 0 sleep 2 (0 = no limit) -> exit 0 (~2 s)
  xargs over timeout, 4 args, each sleeps for the argument in seconds, limit 1 s:
    xargs -P4 -n1 timeout 1 sleep (2 and 3 exceed the limit) -> xargs exit 123
    and timeout around xargs: timeout 1 xargs -P2 -n1 sleep, input 5 5 5 5 -> exit 124
[5] does timeout kill grandchildren? (sh runs a background 'sleep 6X.907' and waits; pgrep -f counts survivors 0.5 s after exit):
  default, sleep in same process group  -> exit 124; sleep alive after: 0
  --foreground, sleep in same group      -> exit 124; sleep alive after: 1
  default, sleep started with setsid     -> exit 124; sleep alive after: 1
  default, sh ignores TERM, sleep in group, no -k -> exit 124; sleep alive after: 0
  -s KILL, sleep in same group           -> exit 137; sleep alive after: 0
  default, exec sleep (no grandchild)    -> exit 124; sleep alive after: 0

Lo que se ve

Qué significa

En un script con xargs -P, la salida de trabajos que escriben líneas largas debe ir a un fichero por trabajo (por ejemplo -I{} sh -c 'cmd {} > "out.{}"'), no a la misma tubería; no se probó esa variante aquí, solo el caso de la tubería y el de un único fichero compartido. Para saber qué falló, el 123 no basta: el hijo debe registrar él mismo su resultado. Y un 124 de timeout es una pista, no una prueba: comprobar si la escritura o la copia terminó antes de dar por buena una rutina, y si el comando lanza procesos que se separan del grupo, timeout no los alcanza. Nada de esto sustituye a probar los scripts propios con un directorio de prueba: se midió con sleep y sh, no con los comandos reales de cada uno.

Script completo

#!/bin/bash
# xargs -P and timeout, measured on GNU findutils/coreutils in a throwaway dir under mktemp -d:
# process counts (-n, -I, empty input), output interleaving of parallel jobs, xargs exit status 123-127,
# timeout exit codes, and whether timeout kills grandchildren (--foreground, setsid).
# Usage: test-xargs-p-timeout.sh
export LC_ALL=C.UTF-8
W=$(mktemp -d /tmp/xargsp.XXXXXX) || exit 1
case $W in /tmp/xargsp.*) ;; *) echo "bad workdir" >&2; exit 1;; esac
TAG=$((RANDOM % 900 + 100))   # makes the sleep durations of the grandchildren unique to this run
cleanup(){ pkill -f "sleep 6[0-9]\.$TAG" 2>/dev/null; rm -rf "$W"; }
trap cleanup EXIT
mkdir "$W/bin"
# counting wrapper: one line per process with its argument count
printf '#!/bin/sh\necho "$#" >> "%s/calls"\nexit 0\n' "$W" > "$W/bin/count"
# writer: python3 w.py CHAR LENGTH COUNT -> COUNT lines of LENGTH copies of CHAR, one write() per line
cat > "$W/bin/w.py" <<'PY'
import os, sys
c, n, k = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
line = (c * n + "\n").encode()
for _ in range(k):
    os.write(1, line)
PY
# failing wrapper: exits with $1 when its second argument is 3, else 0
printf '#!/bin/sh\necho "$2" >> "%s/ran"\n[ "$2" = 3 ] && exit "$1"\nexit 0\n' "$W" > "$W/bin/failat3"
printf '#!/bin/sh\nexit 0\n' > "$W/bin/noexec"
printf 'not a program\n' > "$W/bin/notexec"
chmod 755 "$W"/bin/count "$W"/bin/failat3 "$W"/bin/noexec; chmod 644 "$W/bin/notexec"
xargs --version | head -1; timeout --version | head -1; echo "kernel: $(uname -sr)"

echo "[1] number of processes started by xargs on 10 arguments (args per process from the wrapper):"
echo -n "  xargs count                 -> "; seq 10 | { rm -f "$W/calls"; xargs "$W/bin/count"; printf '%s processes; args: %s\n' "$(wc -l < "$W/calls")" "$(paste -sd, "$W/calls")"; }
echo -n "  xargs -n3 count             -> "; seq 10 | { rm -f "$W/calls"; xargs -n3 "$W/bin/count"; printf '%s processes; args: %s\n' "$(wc -l < "$W/calls")" "$(paste -sd, "$W/calls")"; }
echo -n "  xargs -P4 -n3 count         -> "; seq 10 | { rm -f "$W/calls"; xargs -P4 -n3 "$W/bin/count"; printf '%s processes; args: %s\n' "$(wc -l < "$W/calls")" "$(sort -n "$W/calls" | paste -sd,)"; }
echo -n "  xargs -I{} count {}         -> "; seq 10 | { rm -f "$W/calls"; xargs -I{} "$W/bin/count" {}; printf '%s processes; args: %s\n' "$(wc -l < "$W/calls")" "$(paste -sd, "$W/calls")"; }
echo -n "  xargs -I{} -n3 count {}     -> "; seq 10 | { rm -f "$W/calls"; xargs -I{} -n3 "$W/bin/count" {} 2>&1; printf '%s processes; args: %s\n' "$(wc -l < "$W/calls" 2>/dev/null || echo 0)" "$(paste -sd, "$W/calls" 2>/dev/null)"; }
echo -n "  xargs -I{} count {} {}      -> "; seq 10 | { rm -f "$W/calls"; xargs -I{} "$W/bin/count" {} {}; printf '%s processes; args: %s\n' "$(wc -l < "$W/calls")" "$(paste -sd, "$W/calls")"; }
echo -n "  empty input, xargs count    -> "; : | { rm -f "$W/calls"; xargs "$W/bin/count"; printf '%s processes; args: %s\n' "$(wc -l < "$W/calls" 2>/dev/null || echo 0)" "$(paste -sd, "$W/calls" 2>/dev/null)"; }
echo -n "  empty input, xargs -r count -> "; : | { rm -f "$W/calls"; xargs -r "$W/bin/count"; : >> "$W/calls"; printf '%s processes; args: %s\n' "$(wc -l < "$W/calls" 2>/dev/null || echo 0)" "$(paste -sd, "$W/calls" 2>/dev/null)"; }

echo "[2] output interleaving, 8 jobs with xargs -P8 -I{}, one write() per line (lines pure = consist of one single letter):"
inter(){ # $1 sink (pipe|file) $2 line length $3 lines per job
  local out="$W/out"; : > "$out"
  if [ "$1" = pipe ]; then
    printf 'A\nB\nC\nD\nE\nF\nG\nH\n' | xargs -P8 -I{} python3 "$W/bin/w.py" {} "$2" "$3" | cat > "$out"
  else
    printf 'A\nB\nC\nD\nE\nF\nG\nH\n' | xargs -P8 -I{} python3 "$W/bin/w.py" {} "$2" "$3" > "$out"
  fi
  local total pure
  total=$(wc -l < "$out"); pure=$(grep -cE '^(A+|B+|C+|D+|E+|F+|G+|H+)$' "$out")
  echo "  sink=$1 line=$2 chars x $3 lines per job: expected lines: $(( 8 * $3 )); lines in output: $total; pure lines of the right length: $(awk -v n="$2" '$0 ~ /^(A+|B+|C+|D+|E+|F+|G+|H+)$/ && length($0)==n' "$out" | wc -l)"
}
inter pipe 100 1000
inter pipe 4000 500
inter pipe 200000 20
inter file 200000 20

echo "[3] exit status of xargs when a child fails (10 args, -n1, failat3 returns the given status only for 3):"
for st in 1 2 100 255; do
  rm -f "$W/ran"; seq 10 | xargs -n1 "$W/bin/failat3" $st 2>"$W/err"; rc=$?
  echo "  child exits $st -> xargs exit $rc; children run: $(wc -l < "$W/ran"); stderr: $(head -c 120 "$W/err" | tr '\n' ' ')"
done
rm -f "$W/ran"; seq 10 | xargs -P3 -n1 "$W/bin/failat3" 1 2>/dev/null; echo "  -P3, child exits 1 -> xargs exit $?; children run: $(wc -l < "$W/ran")"
echo -n "  child killed by SIGKILL -> "; seq 2 | xargs -n1 sh -c 'kill -9 $$' x 2>"$W/err"; echo "xargs exit $?; stderr: $(head -c 120 "$W/err" | tr '\n' ' ')"
echo -n "  child killed by SIGTERM -> "; seq 2 | xargs -n1 sh -c 'kill -TERM $$' x 2>"$W/err"; echo "xargs exit $?; stderr: $(head -c 120 "$W/err" | tr '\n' ' ')"
echo -n "  command not executable (mode 644) -> "; echo 1 | xargs "$W/bin/notexec" 2>"$W/err"; echo "xargs exit $?"
echo -n "  command not found -> "; echo 1 | xargs nonexistent-cmd-xyz 2>"$W/err"; echo "xargs exit $?"
echo -n "  invalid option -> "; echo 1 | xargs --nonsense true 2>"$W/err"; echo "xargs exit $?"
echo -n "  argument list too long for one -s size -> "; seq 3 | xargs -s 3 true 2>"$W/err"; echo "xargs exit $? ($(head -c 80 "$W/err"))"
echo -n "  sh -c 'exit 0' -> "; seq 3 | xargs -n1 sh -c 'exit 0' x; echo "xargs exit $?"
echo -n "  child exits 1, then the same with '|| true' wrapper in sh -c -> "; seq 3 | xargs -n1 sh -c 'false || true' x; echo "xargs exit $?"

echo "[4] timeout exit codes (limit 1 s):"
# note: when the command dies from a signal the shell reports 128+signal; "Killed" job messages are silenced
t(){ { local label=$1; shift; local s=$SECONDS; "$@" 2>"$W/err"; local rc=$?; echo "  $label -> exit $rc (~$((SECONDS - s)) s)"; } 2>/dev/null; }
t "timeout 1 sleep 5" timeout 1 sleep 5
t "timeout -s KILL 1 sleep 5" timeout -s KILL 1 sleep 5
t "timeout -s INT 1 sleep 5" timeout -s INT 1 sleep 5
t "timeout --preserve-status 1 sleep 5" timeout --preserve-status 1 sleep 5
t "timeout 1 sh -c 'trap \"\" TERM; sleep 5'" timeout 1 sh -c 'trap "" TERM; sleep 3'
t "timeout -k 1 1 sh -c 'trap \"\" TERM; sleep 5'" timeout -k 1 1 sh -c 'trap "" TERM; sleep 5'
t "timeout 5 sh -c 'exit 3'" timeout 5 sh -c 'exit 3'
t "timeout 5 sh -c 'exit 124' (child itself)" timeout 5 sh -c 'exit 124'
t "timeout 5 sh -c 'kill -9 \$\$' (child killed by itself)" timeout 5 sh -c 'kill -9 $$'
t "timeout 5 nonexistent-cmd-xyz" timeout 5 nonexistent-cmd-xyz
t "timeout 5 notexec (mode 644)" timeout 5 "$W/bin/notexec"
t "timeout abc sleep 1 (invalid duration)" timeout abc sleep 1
t "timeout --nonsense 1 sleep 1" timeout --nonsense 1 sleep 1
t "timeout 0 sleep 2 (0 = no limit)" timeout 0 sleep 2
echo "  xargs over timeout, 4 args, each sleeps for the argument in seconds, limit 1 s:"
seq 0 3 | xargs -P4 -n1 timeout 1 sleep 2>/dev/null; echo "    xargs -P4 -n1 timeout 1 sleep (2 and 3 exceed the limit) -> xargs exit $?"
echo "    and timeout around xargs: timeout 1 xargs -P2 -n1 sleep, input 5 5 5 5 -> exit $(printf '5\n5\n5\n5\n' | timeout 1 xargs -P2 -n1 sleep 2>/dev/null; echo $?)"

echo "[5] does timeout kill grandchildren? (sh runs a background 'sleep 6X.$TAG' and waits; pgrep -f counts survivors 0.5 s after exit):"
surv(){ sleep 0.5; pgrep -fc "sleep $1" ; }
timeout 1 sh -c "sleep 61.$TAG & wait" 2>/dev/null; echo "  default, sleep in same process group  -> exit $?; sleep alive after: $(surv 61.$TAG)"
pkill -f "sleep 61.$TAG" 2>/dev/null
timeout --foreground 1 sh -c "sleep 62.$TAG & wait" 2>/dev/null; echo "  --foreground, sleep in same group      -> exit $?; sleep alive after: $(surv 62.$TAG)"
pkill -f "sleep 62.$TAG" 2>/dev/null
timeout 1 sh -c "setsid sleep 63.$TAG & wait" 2>/dev/null; echo "  default, sleep started with setsid     -> exit $?; sleep alive after: $(surv 63.$TAG)"
pkill -f "sleep 63.$TAG" 2>/dev/null
timeout 1 sh -c "trap '' TERM; sleep 64.$TAG & wait" 2>/dev/null; echo "  default, sh ignores TERM, sleep in group, no -k -> exit $?; sleep alive after: $(surv 64.$TAG)"
pkill -f "sleep 64.$TAG" 2>/dev/null
{ timeout -s KILL 1 sh -c "sleep 65.$TAG & wait"; echo "  -s KILL, sleep in same group           -> exit $?; sleep alive after: $(surv 65.$TAG)"; } 2>/dev/null
pkill -f "sleep 65.$TAG" 2>/dev/null
timeout 1 sh -c "exec sleep 66.$TAG" 2>/dev/null; echo "  default, exec sleep (no grandchild)    -> exit $?; sleep alive after: $(surv 66.$TAG)"

Este artículo no contiene enlaces de afiliado.