2 * FCRON - periodic command scheduler
4 * Copyright 2000-2016 Thibault Godouet <fcron@free.fr>
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.
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.
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
20 * The GNU General Public License can also be found in the file
21 * `LICENSE' that comes with the fcron source distribution.
26 #include "temp_file.h"
29 extern char *tmp_path;
30 extern char debug_opt;
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. */
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
47 if (fchmod(fd, S_IWUSR | S_IRUSR) != 0)
48 die_e("Can't fchmod temp file");
50 const int max_retries = 50;
51 char *name_local = NULL;
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,
62 /* I'm not sure we actually need to be so persistent here */
63 } while (fd == -1 && errno == EEXIST && i < max_retries);
65 die_e("Can't open temporary file");
67 if (name == NULL && unlink(name_local) != 0)
68 die_e("Can't unlink temporary file %s", name_local);
70 fcntl(fd, F_SETFD, 1); /* set close-on-exec flag */
72 /* give the name of the temp file if necessary */
74 *name = strdup2(name_local);