Shell Script mktemp, what’s the best method to create temporary named pipe?

I’m aware its best to create temporary files with mktemp, but what about named pipes?

I prefer things to be as POSIX compliant as possible, but Linux only is acceptable. Avoiding Bashisms is my only hard criteria, as I write in dash.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

tmppipe=$(mktemp -u)
mkfifo -m 600 "$tmppipe"

Unlike regular file creation, which is prone to being hijacked by an existing file or a symbolic link, the creation of a name pipe through mkfifo or the underlying function either creates a new file in the specified place or fails. Something like : >foo is unsafe because if the attacker can predict the output of mktemp then the attacker can create the target file for himself. But mkfifo foo would fail in such a scenario.

If you need full POSIX portability, mkfifo -m 600 /tmp/myfifo is safe against hijacking but prone to a denial of service; without access to a strong random file name generator, you would need to manage retry attempts.

If you don’t care for the subtle security problems around temporary files, you can follow a simple rule: create a private directory, and keep everything in there.

tmpdir=
cleanup () {
  trap - EXIT
  if [ -n "$tmpdir" ] ; then rm -rf "$tmpdir"; fi
  if [ -n "$1" ]; then trap - $1; kill -$1 $$; fi
}
tmpdir=$(mktemp -d)
trap 'cleanup' EXIT
trap 'cleanup HUP' HUP
trap 'cleanup TERM' TERM
trap 'cleanup INT' INT
mkfifo "$tmpdir/pipe"

Method 2

A safer alternative is to use mktemp to create a directory safely, then put your named pipe inside that directory, do an rm -R $dir to get rid of it in the end.

Method 3

Use the “dry-run” option:

mkfifo $(mktemp -ut pipe.XXX)

Method 4

You can use mktemp to create a temporary file, then delete it and create a named pipe with the same name.

For example:

TMPPIPE=$(mktemp -t pipe.XXX) && {
    rm -f $TMPPIPE
    mkfifo $TMPPIPE
}

Method 5

Use mkfifo or mknod in Unix, where by two separate processes can access the pipe by name — one process can open it as a reader, and the other as a writer.

mkfifo my_pipe
gzip -9 -c < my_pipe > out.gz
cat file > my_pipe

The named pipe can be deleted just like any file:

rm my_pipe

mkfifo --mode=0666 /tmp/namedPipe
gzip --stdout -d file.gz > /tmp/namedPipe

NamedPipe can be used a regular file for only reading once.

http://www.linuxjournal.com/article/2156


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x