]>
git.ipfire.org Git - thirdparty/util-linux.git/blob - lib/fileutils.c
2 * Copyright (C) 2012 Sami Kerola <kerolasa@iki.fi>
10 #include <sys/resource.h>
13 #include "fileutils.h"
14 #include "pathnames.h"
16 int mkstemp_cloexec(char *template)
19 return mkostemp(template, O_RDWR
|O_CREAT
|O_EXCL
|O_CLOEXEC
);
21 int fd
, old_flags
, errno_save
;
23 fd
= mkstemp(template);
27 old_flags
= fcntl(fd
, F_GETFD
, 0);
30 if (fcntl(fd
, F_SETFD
, old_flags
| O_CLOEXEC
) < 0)
45 /* Create open temporary file in safe way. Please notice that the
46 * file permissions are -rw------- by default. */
47 int xmkstemp(char **tmpname
, const char *dir
, const char *prefix
)
54 /* Some use cases must be capable of being moved atomically
55 * with rename(2), which is the reason why dir is here. */
56 tmpenv
= dir
? dir
: getenv("TMPDIR");
60 rc
= asprintf(&localtmp
, "%s/%s.XXXXXX", tmpenv
, prefix
);
64 old_mode
= umask(077);
65 fd
= mkstemp_cloexec(localtmp
);
75 int dup_fd_cloexec(int oldfd
, int lowfd
)
77 int fd
, flags
, errno_save
;
79 #ifdef F_DUPFD_CLOEXEC
80 fd
= fcntl(oldfd
, F_DUPFD_CLOEXEC
, lowfd
);
89 flags
= fcntl(fd
, F_GETFD
);
92 if (fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
) < 0)
106 * portable getdtablesize()
108 int get_fd_tabsize(void)
112 #if defined(HAVE_GETDTABLESIZE)
114 #elif defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
117 getrlimit(RLIMIT_NOFILE
, &rl
);
119 #elif defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
120 m
= sysconf(_SC_OPEN_MAX
);
127 #ifdef TEST_PROGRAM_FILEUTILS
132 f
= xfmkstemp(&tmpname
, NULL
, "test");
141 int mkdir_p(const char *path
, mode_t mode
)
149 dir
= p
= strdup(path
);
157 char *e
= strchr(p
, '/');
161 rc
= mkdir(dir
, mode
);
162 if (rc
&& errno
!= EEXIST
)
176 /* returns basename and keeps dirname in the @path, if @path is "/" (root)
177 * then returns empty string */
178 char *stripoff_last_component(char *path
)
180 char *p
= path
? strrchr(path
, '/') : NULL
;