I'm using dd with "excl" option. If interrupted with CTRL+C "dd" leaves the the file it has created and not finished to write. I need to clean it up in such case with the trap INT. However, I don't know how to test in such case whether the file existed already before or it was created by dd. In other words whether "excl" has initiated exit from dd or something else. Exit status might not tell it right inside the trap, since other commands can return the same code. Putting the if [ -e file ] before dd would work, but is not atomic. The file can get created by some other app in between. Just need some elegant solution.
|
show 1 more comment
feedback
|
|
bash and file redirection:
cleanup() {
exec {fd}>&-
rm -f "$out"
}
set -e
set -o noclobber
# with noclobber, redirection will fail if output file exists
exec {fd}>"$out" || exit 3
trap "cleanup; exit 4" INT TERM ERR EXIT
# write to already opened file
dd if=/dev/zero of=/dev/fd/$fd bs=256k count=$(( size*4 ))
# alternative to /dev/fd/$fd is redirecting with >&$fd
exec {fd}>&-
Temporary files:
cleanup() {
rm -f "$temp"
}
set -e
temp=$(mktemp "${out}_XXXXXX") || exit 3
trap "cleanup; exit 4" INT TERM ERR EXIT
dd if=/dev/zero of="$temp" bs=256k count=$(( size*4 ))
mv -n "$temp" "$out"
| |||||||||||||||
feedback
|
set +e; if [ -e "$out" ]; then exit 3; fi; dd if=/dev/zero of="$out${$}" bs=256K count=$(($size*4)) conv=excl || { rm -rf $out${$}; exit 4; } mv -n "$out${$}" "$out" || { rm -rf $out${$}; exit 5; } trap cleanup INT TERM ERR EXIT set -e– azerIO May 12 '11 at 14:06"$out\$"existed before or was created by you. – grawity May 12 '11 at 16:08${$}equals\$for some reason.) However, PIDs are only unique for a very short time. I'm used to multi-user servers, so I tend to consider the possibility of network-mounted directories or of malicious users trying to guess the filename... and of course, junk left over after a program crash. Most programs usemktempor similar methods to ensure the uniqueness of a temporary file. – grawity May 12 '11 at 19:25