mktemp: don't leave file behind on write failure
authorEric Blake <ebb9@byu.net>
Wed, 4 Nov 2009 21:02:20 +0000 (14:02 -0700)
committerEric Blake <ebb9@byu.net>
Thu, 5 Nov 2009 13:53:21 +0000 (06:53 -0700)
* src/mktemp.c (main): Remove just-created file if stdout had
problems.
* bootstrap.conf (gnulib_modules): Add remove.
* tests/misc/close-stdout: Test it.
* NEWS: Document it.

NEWS
bootstrap.conf
src/mktemp.c
tests/misc/close-stdout

diff --git a/NEWS b/NEWS
index ffecd86bee997a96289807f211d607ca222778ec..07eecab1fc177471877d33fe529dcaadc338fa55 100644 (file)
--- a/NEWS
+++ b/NEWS
@@ -20,6 +20,10 @@ GNU coreutils NEWS                                    -*- outline -*-
   This also affected sum, sha1sum, sha224sum, sha384sum and sha512sum.
   [the bug dates back to the initial implementation]
 
+  mktemp no longer leaves a temporary file behind if it was unable to
+  output the name of the file to stdout.
+  [the bug dates back to the initial implementation]
+
   nice -n -1 PROGRAM now runs PROGRAM even when its internal setpriority
   call fails with errno == EACCES.
   [the bug dates back to the initial implementation]
index 79605460efeb40ad3f9841770a717cf9283e8f41..b3a82e0ce85fce09042f770cb713905e7a210038 100644 (file)
@@ -180,6 +180,7 @@ gnulib_modules="
   readutmp
   realloc
   regex
+  remove
   rename
   rmdir
   root-dev-ino
index 808efa91480ec2fa6b5ed71bf192921eeceeacf4..2b6e4b45faabaee686a53027f1f7386471beb6a2 100644 (file)
@@ -23,6 +23,7 @@
 
 #include "system.h"
 
+#include "close-stream.h"
 #include "error.h"
 #include "filenamecat.h"
 #include "quote.h"
@@ -277,7 +278,17 @@ main (int argc, char **argv)
     }
 
   if (status == EXIT_SUCCESS)
-    puts (dest_name);
+    {
+      puts (dest_name);
+      /* If we created a file, but then failed to output the file
+         name, we should clean up the mess before failing.  */
+      if (!dry_run && close_stream (stdout))
+        {
+          int saved_errno = errno;
+          remove (dest_name);
+          error (EXIT_FAILURE, saved_errno, _("write error"));
+        }
+    }
 
 #ifdef lint
   free (dest_name);
index fec1addc80273b656be0d5a284671189f29e3437..852c3c822340271c59eb5573783ec62bb112f66f 100755 (executable)
@@ -50,12 +50,18 @@ if "$p/src/test" -w /dev/stdout >/dev/null &&
    "$p/src/test" ! -w /dev/stdout >&-; then
   "$p/src/printf" 'foo' >&- 2>/dev/null && fail=1
   cp --verbose a b >&- 2>/dev/null && fail=1
+  rm -Rf tmpfile-?????? || fail=1
+  mktemp tmpfile-XXXXXX >&- 2>/dev/null && fail=1
+  test -e tmpfile-?????? && fail=1
 fi
 
 # Likewise for /dev/full, if /dev/full works.
 if test -w /dev/full && test -c /dev/full; then
   "$p/src/printf" 'foo' >/dev/full 2>/dev/null && fail=1
   cp --verbose a b >/dev/full 2>/dev/null && fail=1
+  rm -Rf tmpdir-?????? || fail=1
+  mktemp -d tmpdir-XXXXXX >/dev/full 2>/dev/null && fail=1
+  test -e tmpdir-?????? && fail=1
 fi
 
 Exit $fail