Home > Back-end >  bash redirect how to open file with O_CLOEXEC flag to prevent command inherit the fd
bash redirect how to open file with O_CLOEXEC flag to prevent command inherit the fd

Time:11-12

the bash Redirections can't specified O_CLOEXEC flag when open() file, but sometimes we need it.

{
    flock -x 9
    ./do_some_work
} 9< lock

do_some_work will inherit the fd 9. if do_some_work unlock fd 9. then the lock will be buggy.

as KamiCuk's solution

{
    flock -x 9
    {
         do_work1
         do_work2
    } <&9-
} 9< lock

CodePudding user response:

how to open file with O_CLOEXEC flag

It's not possible. You have to write small a Bash built-in that will open the file descriptor. I would imagine:

cloexec 9 file
flock -x 9
stuff
exec <&9-

to prevent command inherit the fd

To prevent a command from inheriting a file descriptor, close it.

command <&9-
  •  Tags:  
  • bash
  • Related