Refactor code for reading process environment from procfs

This commit is contained in:
Benny Baumann 2020-10-26 19:18:29 +01:00 committed by cgzones
parent a3bb7cbe64
commit c98d4577c9
1 changed files with 27 additions and 16 deletions

View File

@ -263,24 +263,35 @@ char* Platform_getProcessEnv(pid_t pid) {
char procname[128]; char procname[128];
xSnprintf(procname, sizeof(procname), PROCDIR "/%d/environ", pid); xSnprintf(procname, sizeof(procname), PROCDIR "/%d/environ", pid);
FILE* fd = fopen(procname, "r"); FILE* fd = fopen(procname, "r");
if(!fd)
return NULL;
char *env = NULL; char *env = NULL;
if (fd) {
size_t capacity = 4096, size = 0, bytes; size_t capacity = 0;
env = xMalloc(capacity); size_t size = 0;
while ((bytes = fread(env+size, 1, capacity-size, fd)) > 0) { ssize_t bytes = 0;
do {
size += bytes; size += bytes;
capacity *= 2; capacity += 4096;
env = xRealloc(env, capacity); env = xRealloc(env, capacity);
} } while ((bytes = fread(env + size, 1, capacity - size, fd)) > 0);
fclose(fd); fclose(fd);
if (size < 2 || env[size-1] || env[size-2]) {
if (size + 2 < capacity) { if (bytes < 0) {
env = xRealloc(env, capacity+2); free(env);
} return NULL;
env[size] = 0;
env[size+1] = 0;
}
} }
size += bytes;
env = xRealloc(env, size + 2);
env[size] = '\0';
env[size+1] = '\0';
return env; return env;
} }