summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBenny Baumann <BenBE@geshi.org>2020-10-26 19:18:29 +0100
committercgzones <cgzones@googlemail.com>2020-10-27 17:54:37 +0100
commitc98d4577c998047d7bd32c18b3802dd2bc09a634 (patch)
treebcadc3621472c726d401a411cc9e839ee912755f
parenta3bb7cbe649d9c718b65aded4c6b2445ff5d20d5 (diff)
Refactor code for reading process environment from procfs
-rw-r--r--linux/Platform.c43
1 files changed, 27 insertions, 16 deletions
diff --git a/linux/Platform.c b/linux/Platform.c
index 64180484..43bf84b1 100644
--- a/linux/Platform.c
+++ b/linux/Platform.c
@@ -263,24 +263,35 @@ char* Platform_getProcessEnv(pid_t pid) {
char procname[128];
xSnprintf(procname, sizeof(procname), PROCDIR "/%d/environ", pid);
FILE* fd = fopen(procname, "r");
+ if(!fd)
+ return NULL;
+
char *env = NULL;
- if (fd) {
- size_t capacity = 4096, size = 0, bytes;
- env = xMalloc(capacity);
- while ((bytes = fread(env+size, 1, capacity-size, fd)) > 0) {
- size += bytes;
- capacity *= 2;
- env = xRealloc(env, capacity);
- }
- fclose(fd);
- if (size < 2 || env[size-1] || env[size-2]) {
- if (size + 2 < capacity) {
- env = xRealloc(env, capacity+2);
- }
- env[size] = 0;
- env[size+1] = 0;
- }
+
+ size_t capacity = 0;
+ size_t size = 0;
+ ssize_t bytes = 0;
+
+ do {
+ size += bytes;
+ capacity += 4096;
+ env = xRealloc(env, capacity);
+ } while ((bytes = fread(env + size, 1, capacity - size, fd)) > 0);
+
+ fclose(fd);
+
+ if (bytes < 0) {
+ free(env);
+ return NULL;
}
+
+ size += bytes;
+
+ env = xRealloc(env, size + 2);
+
+ env[size] = '\0';
+ env[size+1] = '\0';
+
return env;
}

© 2014-2024 Faster IT GmbH | imprint | privacy policy