Skip to content

Commit aa95f0b

Browse files
committed
tmpfiles: refactor code into new is_dir_empty function
The existing implementation seemed useful enough to warrant a new helper function. Care was taken to ensure the revised code no longer suffers any memory leaks.
1 parent 2957246 commit aa95f0b

File tree

2 files changed

+19
-12
lines changed

2 files changed

+19
-12
lines changed

src/helpers.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
#define FINIT_HELPERS_H_
2727

2828
#include <ctype.h>
29+
#include <dirent.h>
2930
#include <fcntl.h>
3031
#include <stdarg.h>
3132
#include <stdlib.h>
@@ -206,6 +207,22 @@ static inline char *fgetval(const char *line, const char *key, char *sep)
206207
return realloc(copy, len);
207208
}
208209

210+
static inline int is_dir_empty(const char *path)
211+
{
212+
struct dirent **namelist;
213+
int num;
214+
215+
num = scandir(path, &namelist, NULL, NULL);
216+
if (num < 0)
217+
return 0;
218+
219+
for (int i = 0; i < num; i++)
220+
free(namelist[i]);
221+
free(namelist);
222+
223+
return num >= 3;
224+
}
225+
209226
#endif /* FINIT_HELPERS_H_ */
210227

211228
/**

src/tmpfiles.c

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323

2424
#include "config.h" /* Generated by configure script */
2525

26-
#include <dirent.h>
2726
#include <ftw.h>
2827
#include <getopt.h>
2928
#include <glob.h>
@@ -394,17 +393,8 @@ static void tmpfiles(char *line)
394393
paste(buf, sizeof(buf), "/usr/share/factory", path);
395394
arg = buf;
396395
}
397-
if (!strc) {
398-
struct dirent **namelist;
399-
int num;
400-
401-
if (!S_ISDIR(st.st_mode))
402-
break;
403-
num = scandir(path, &namelist, NULL, NULL);
404-
free(namelist);
405-
if (num >= 3)
406-
break; /* not empty */
407-
}
396+
if (fisdir(path) && !is_dir_empty(path)) {
397+
break;
408398
if (fisdir(arg) && !fisslashdir(arg)) {
409399
size_t len = strlen(arg) + 2;
410400

0 commit comments

Comments
 (0)