summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/shared/util.c30
-rw-r--r--src/shared/util.h9
2 files changed, 16 insertions, 23 deletions
diff --git a/src/shared/util.c b/src/shared/util.c
index 5b795d4a24..1d30ea5851 100644
--- a/src/shared/util.c
+++ b/src/shared/util.c
@@ -1063,10 +1063,10 @@ int get_process_exe(pid_t pid, char **name) {
}
static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
- char *p;
- FILE *f;
- int r;
+ _cleanup_fclose_ FILE *f = NULL;
+ _cleanup_free_ char *p = NULL;
+ assert(field);
assert(uid);
if (pid == 0)
@@ -1076,21 +1076,11 @@ static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
return -ENOMEM;
f = fopen(p, "re");
- free(p);
-
if (!f)
return -errno;
- while (!feof(f)) {
- char line[LINE_MAX], *l;
-
- if (!fgets(line, sizeof(line), f)) {
- if (feof(f))
- break;
-
- r = -errno;
- goto finish;
- }
+ FOREACH_LINE(f, line, return -errno) {
+ char *l;
l = strstrip(line);
@@ -1100,17 +1090,11 @@ static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
l[strcspn(l, WHITESPACE)] = 0;
- r = parse_uid(l, uid);
- goto finish;
+ return parse_uid(l, uid);
}
}
- r = -EIO;
-
-finish:
- fclose(f);
-
- return r;
+ return -EIO;
}
int get_process_uid(pid_t pid, uid_t *uid) {
diff --git a/src/shared/util.h b/src/shared/util.h
index 18494f14f2..d926b01919 100644
--- a/src/shared/util.h
+++ b/src/shared/util.h
@@ -567,3 +567,12 @@ char *strreplace(const char *text, const char *old_string, const char *new_strin
char *strip_tab_ansi(char **p, size_t *l);
int on_ac_power(void);
+
+#define FOREACH_LINE(f, line, on_error) \
+ for (char line[LINE_MAX]; !feof(f); ) \
+ if (!fgets(line, sizeof(line), f)) { \
+ if (ferror(f)) { \
+ on_error; \
+ } \
+ break; \
+ } else