aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorHeikki Linnakangas <heikki.linnakangas@iki.fi>2012-10-18 22:26:26 +0300
committerHeikki Linnakangas <heikki.linnakangas@iki.fi>2012-10-18 22:30:38 +0300
commite7bab081a9f726fa8cd910bd7e2567423383b44b (patch)
tree2f454f7d3aa017e7e7dcff8317e01a489de71b57 /src
parent623e49c0c03a1ff1b0992a20c0e2fdaaa6d13f34 (diff)
downloadpostgresql-e7bab081a9f726fa8cd910bd7e2567423383b44b.tar.gz
postgresql-e7bab081a9f726fa8cd910bd7e2567423383b44b.zip
Further tweaking of the readfile() function in pg_ctl.
Don't leak a file descriptor if the file is empty or we can't read its size. Expect there to be a newline at the end of the last line, too. If there isn't, ignore anything after the last newline. This makes it a tiny bit more robust in case the file is appended to concurrently, so that we don't return the last line if it hasn't been fully written yet. And this makes the code a bit less obscure, anyway. Per Tom Lane's suggestion. Backpatch to all supported branches.
Diffstat (limited to 'src')
-rw-r--r--src/bin/pg_ctl/pg_ctl.c15
1 files changed, 11 insertions, 4 deletions
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 97bdeb10af0..32fce00d760 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -333,10 +333,14 @@ readfile(const char *path)
if (fd < 0)
return NULL;
if (fstat(fd, &statbuf) < 0)
+ {
+ close(fd);
return NULL;
+ }
if (statbuf.st_size == 0)
{
/* empty file */
+ close(fd);
result = (char **) pg_malloc(sizeof(char *));
*result = NULL;
return result;
@@ -352,14 +356,17 @@ readfile(const char *path)
return NULL;
}
- /* count newlines */
+ /*
+ * Count newlines. We expect there to be a newline after each full line,
+ * including one at the end of file. If there isn't a newline at the end,
+ * any characters after the last newline will be ignored.
+ */
nlines = 0;
- for (i = 0; i < len - 1; i++)
+ for (i = 0; i < len; i++)
{
if (buffer[i] == '\n')
nlines++;
}
- nlines++; /* account for the last line */
/* set up the result buffer */
result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
@@ -369,7 +376,7 @@ readfile(const char *path)
n = 0;
for (i = 0; i < len; i++)
{
- if (buffer[i] == '\n' || i == len - 1)
+ if (buffer[i] == '\n')
{
int slen = &buffer[i] - linebegin + 1;
char *linebuf = pg_malloc(slen + 1);