* lib/sys_time_.h: Use a recursion-safe inclusion guard rather than
[gnulib.git] / lib / tmpfile-safer.c
1 /* Invoke tmpfile, but avoid some glitches.
2    Copyright (C) 2006 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 /* Written by Eric Blake, based on ideas from Paul Eggert.  */
19
20 #include <config.h>
21
22 #include "stdio-safer.h"
23
24 #include <errno.h>
25 #include <unistd.h>
26 #include "unistd-safer.h"
27
28 #include "binary-io.h"
29
30 #ifndef STDERR_FILENO
31 # define STDERR_FILENO 2
32 #endif
33
34 /* Like tmpfile, but do not return stdin, stdout, or stderr.
35
36    Remember that tmpfile can leave files behind if your program calls _exit,
37    so this function should not be mixed with the close_stdout module.  */
38
39 FILE *
40 tmpfile_safer (void)
41 {
42   FILE *fp = tmpfile ();
43
44   if (fp)
45     {
46       int fd = fileno (fp);
47
48       if (0 <= fd && fd <= STDERR_FILENO)
49         {
50           int f = dup_safer (fd);
51
52           if (f < 0)
53             {
54               int e = errno;
55               fclose (fp);
56               errno = e;
57               return NULL;
58             }
59
60           /* Keep the temporary file in binary mode, on platforms
61              where that matters.  */
62           if (fclose (fp) != 0
63               || ! (fp = fdopen (f, O_BINARY ? "wb+" : "w+")))
64             {
65               int e = errno;
66               close (f);
67               errno = e;
68               return NULL;
69             }
70         }
71     }
72
73   return fp;
74 }