Skip to main content
added 1104 characters in body
Source Link
Petr Skocik
  • 29.7k
  • 18
  • 90
  • 154

As far as I know, no. You have to close it manually:

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

If you want to get extra hacky, you can set the flag by calling the fcntl function directly via 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

Output:

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

(Not a typo in pasting -- the 9 really did get closed when the child bash got execced).

As far as I know, no. You have to close it manually:

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

As far as I know, no. You have to close it manually:

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

If you want to get extra hacky, you can set the flag by calling the fcntl function directly via 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

Output:

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

(Not a typo in pasting -- the 9 really did get closed when the child bash got execced).

Source Link
Petr Skocik
  • 29.7k
  • 18
  • 90
  • 154

As far as I know, no. You have to close it manually:

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