Golpe, tenedor con CLOEXEC

Golpe, tenedor con CLOEXEC

¿Puede Bash ejecutar un subproceso y al mismo tiempo evitar que un subproceso herede un descriptor de archivo?

if flock -nx 9
then
  # If begin program runs away, it will keep the lock.
  begin program
else
  echo "Lock held :/)" >&2
fi 9> /tmp/lk

Respuesta1

Hasta donde yo sé, no. Tienes que cerrarlo manualmente:

if flock 9 -nx
then
   program 9>&- #<= manual close of fd 9 after `program` has forked but before it execs
else
  echo "Lock held :/)" >&2
fi 9> /tmp/lk

Si desea obtener más truco, puede configurar la bandera llamando a la fcntlfunción directamente a través dectypes.sh:

#!/bin/bash

echo initial
ls /proc/$$/fd/

echo with 9
{

ls /proc/$$/fd/

echo with 9 in an execced child
bash -c ' ls /proc/$$/fd/'

} 9</etc/passwd


echo
echo BEGIN MAGIC
FD_CLOEXEC=1
FD_SETFD=2

. ctypes.sh
echo initial
ls /proc/$$/fd/

echo with 9
{

dlcall fcntl int:9 int:$FD_SETFD int:$FD_CLOEXEC

ls /proc/$$/fd/

echo with 9 in an execced child
bash -c ' ls /proc/$$/fd/'

} 9</etc/passwd

Producción:

initial
0
1
2
255
with 9
0
1
2
255
9
with 9 in an execced child
0
1
2
3
9

BEGIN MAGIC
initial
0
1
2
255
with 9
0
1
2
255
9
with 9 in an execced child
0
1
2
3

(No es un error tipográfico al pegar: el 9 realmente se cerró cuando se ejecutó el child bash).

Respuesta2

Con bash 5.0+ y los módulos cargables de ejemplo (debian requiere que también instales el bash-builtinspaquete), puedes usar el módulo cargable fdflags.

if flock -nx 9
then
  enable -f /usr/lib/bash/fdflags fdflags
  fdflags -s+cloexec 9
  begin program
else
  echo "Lock held :/)" >&2
fi 9> /tmp/lk

información relacionada