Index: libgfortran/io/unix.c
===================================================================
--- libgfortran/io/unix.c	(revision 170980)
+++ libgfortran/io/unix.c	(working copy)
@@ -1021,7 +1021,10 @@ tempfile (st_parameter_open *opp)
   const char *tempdir;
   char *template;
   const char *slash = "/";
-  int fd;
+  int fd, tempdirlen;
+#ifndef HAVE_MKSTEMP
+  int count;
+#endif
 
   tempdir = getenv ("GFORTRAN_TMPDIR");
 #ifdef __MINGW32__
@@ -1046,16 +1049,19 @@ tempfile (st_parameter_open *opp)
   if (tempdir == NULL)
     tempdir = DEFAULT_TEMPDIR;
 #endif
+
   /* Check for special case that tempdir contains slash
      or backslash at end.  */
-  if (*tempdir == 0 || tempdir[strlen (tempdir) - 1] == '/'
+  tempdirlen = strlen (tempdir);
+  if (*tempdir == 0 || tempdir[tempdirlen - 1] == '/'
 #ifdef __MINGW32__
-      || tempdir[strlen (tempdir) - 1] == '\\'
+      || tempdir[tempdirlen - 1] == '\\'
 #endif
      )
     slash = "";
 
-  template = get_mem (strlen (tempdir) + 20);
+  // Take care that the template is longer in the mktemp() branch.
+  template = get_mem (tempdirlen + 23);
 
 #ifdef HAVE_MKSTEMP
   sprintf (template, "%s%sgfortrantmpXXXXXX", tempdir, slash);
@@ -1064,11 +1070,29 @@ tempfile (st_parameter_open *opp)
 
 #else /* HAVE_MKSTEMP */
   fd = -1;
+  count = 0;
   do
     {
-      sprintf (template, "%s%sgfortrantmpXXXXXX", tempdir, slash);
+      sprintf (template, "%s%sgfortrantmpaaaXXXXXX", tempdir, slash);
+      if (count > 0)
+	{
+	  int c = count;
+	  template[tempdirlen + strlen (slash) + 13] = 'a' + (c% 26);
+	  c /= 26;
+	  template[tempdirlen + strlen (slash) + 12] = 'a' + (c % 26);
+	  c /= 26;
+	  template[tempdirlen + strlen (slash) + 11] = 'a' + (c % 26);
+	  if (c >= 26)
+	    break;
+	}
+
       if (!mktemp (template))
-	break;
+      {
+	errno = EEXIST;
+	count++;
+	continue;
+      }
+
 #if defined(HAVE_CRLF) && defined(O_BINARY)
       fd = open (template, O_RDWR | O_CREAT | O_EXCL | O_BINARY,
 		 S_IREAD | S_IWRITE);
