diff --git a/proc/readproc.c b/proc/readproc.c index 3e81c6ad..f199c261 100644 --- a/proc/readproc.c +++ b/proc/readproc.c @@ -465,17 +465,20 @@ static char** file2strvec(const char* directory, const char* what) { if(fd==-1) return NULL; /* read whole file into a memory buffer, allocating as we go */ - while ((n = read(fd, buf, sizeof buf - 1)) > 0) { + while ((n = read(fd, buf, sizeof buf - 1)) >= 0) { if (n < (int)(sizeof buf - 1)) end_of_file = 1; - if (n == 0 && rbuf == 0) + if (n == 0 && rbuf == 0) { + close(fd); return NULL; /* process died between our open and read */ + } if (n < 0) { if (rbuf) free(rbuf); + close(fd); return NULL; /* read error */ } - if (end_of_file && buf[n-1]) /* last read char not null */ + if (end_of_file && (n == 0 || buf[n-1]))/* last read char not null */ buf[n++] = '\0'; /* so append null-terminator */ rbuf = xrealloc(rbuf, tot + n); /* allocate more memory */ memcpy(rbuf + tot, buf, n); /* copy buffer into it */