]> granicus.if.org Git - fcron/blob - temp_file.c
fixed typo in install doc
[fcron] / temp_file.c
1 /*
2  * FCRON - periodic command scheduler 
3  *
4  *  Copyright 2000-2014 Thibault Godouet <fcron@free.fr>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  * 
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  * 
20  *  The GNU General Public License can also be found in the file
21  *  `LICENSE' that comes with the fcron source distribution.
22  */
23
24
25 #include "global.h"
26 #include "temp_file.h"
27 #include "mem.h"
28
29 extern char *tmp_path;
30 extern char debug_opt;
31
32
33 int
34 temp_file(char **name)
35     /* Open a temporary file and return its file descriptor */
36     /* Returns the filename to *name if name is not null. */
37     /* (die on error) */
38 {
39     int fd;
40 #ifdef HAVE_MKSTEMP
41     char name_local[PATH_LEN] = "";
42     snprintf(name_local, sizeof(name_local), "%sfcr-XXXXXX", tmp_path);
43     if ((fd = mkstemp(name_local)) == -1)
44         die_e("Can't find a unique temporary filename");
45     /* we must set the file mode to 600 (some versions of mkstemp may set it
46      * incorrectly) */
47     if (fchmod(fd, S_IWUSR | S_IRUSR) != 0)
48         die_e("Can't fchmod temp file");
49 #else
50     const int max_retries = 50;
51     char *name_local = NULL;
52     int i;
53
54     i = 0;
55     do {
56         i++;
57         Set(name_local, tempnam(NULL, NULL));
58         if (name_local == NULL)
59             die("Can't find a unique temporary filename");
60         fd = open(name_local, O_RDWR | O_CREAT | O_EXCL | O_APPEND,
61                   S_IRUSR | S_IWUSR);
62         /* I'm not sure we actually need to be so persistent here */
63     } while (fd == -1 && errno == EEXIST && i < max_retries);
64     if (fd == -1)
65         die_e("Can't open temporary file");
66 #endif
67     if (name == NULL && unlink(name_local) != 0)
68         die_e("Can't unlink temporary file %s", name_local);
69
70     fcntl(fd, F_SETFD, 1);      /* set close-on-exec flag */
71
72     /* give the name of the temp file if necessary */
73     if (name != NULL)
74         *name = strdup2(name_local);
75 #ifndef HAVE_MKSTEMP
76     free(name_local);
77 #endif
78
79     return fd;
80 }