Bash, CLOEXEC를 사용한 포크

Bash, CLOEXEC를 사용한 포크

하위 프로세스가 파일 설명자를 상속하는 것을 방지하면서 Bash가 하위 프로세스를 실행할 수 있습니까?

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

답변1

내가 아는 한, 아니오. 수동으로 닫아야 합니다.

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

추가 해킹을 원할 경우 다음을 fcntl통해 함수를 직접 호출하여 플래그를 설정할 수 있습니다.ctypes.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

산출:

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

(붙여넣기의 오타가 아닙니다. 하위 bash가 실행될 때 9가 실제로 닫혔습니다.)

답변2

bash 5.0+ 및 로드 가능한 모듈 예제(데비안에서는 패키지도 설치해야 함 bash-builtins)를 사용하면 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

관련 정보