Reputation: 298
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
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
trap 'rm --recursive "$working_directory"' EXIT
working_directory="$(mktemp --directory)"
fifo_file="${working_directory}/fifo.pipe"
…
Upvotes: 3