showkey
showkey

Reputation: 298

Why remove the fifo file instantly after attaching to a file descriptor?

fifo_file=fifo.pipe
mkfifo $fifo_file
exec 6<>$fifo_file
rm $fifo_file
some_code_omit

The above bash script create a named pipe,and attach it with a file descriptor 6

exec 6<>$fifo_file

Why remove the fifo file instantly rm $fifo_file after attaching to a file descriptor? Can i write the code as below?

fifo_file=fifo.pipe
mkfifo $fifo_file
exec 6<>$fifo_file
some_code_omit
rm $fifo_file

Is there some difference between them ?
rm $fifo_file means to remove the name of $fifo_file,instead of delete the file $fifo_file,the file still exists there after rm $fifo_file.

Upvotes: 3

Views: 1865

Answers (1)

l0b0
l0b0

Reputation: 58928

By removing the filesystem entry (which leaves the actual file intact until it's closed for reading and writing) after the file has been created and opened for reading and writing you avoid polluting the filesystem with a useless entry. Unfortunately this means that if the script dies before the rm command runs, the mkfifo command will fail on the next run:

$ mkfifo foo
$ mkfifo foo
mkfifo: cannot create fifo 'foo': File exists

A possible improvement here would be to

  1. guarantee the avoidance of a collision by creating a different file on each run,
  2. create the fifo file within a directory only accessible by its creator (assuming you use a sane umask), and
  3. clean up when the script exits without any timing issues:
trap 'rm --recursive "$working_directory"' EXIT
working_directory="$(mktemp --directory)"
fifo_file="${working_directory}/fifo.pipe"
…

Upvotes: 3

Related Questions