Skip to content

Commit 57faaf3

Browse files
committed
Use truncate(2) where appropriate.
When truncating files by name, use truncate(2). Windows hasn't got it, so keep our previous coding based on ftruncate(2) as a fallback. Discussion: https://postgr.es/m/16663-fe97ccf9932fc800%40postgresql.org
1 parent 9f35f94 commit 57faaf3

File tree

3 files changed

+29
-12
lines changed

3 files changed

+29
-12
lines changed

src/backend/storage/file/fd.c

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -622,6 +622,33 @@ pg_flush_data(int fd, off_t offset, off_t nbytes)
622622
#endif
623623
}
624624

625+
/*
626+
* Truncate a file to a given length by name.
627+
*/
628+
int
629+
pg_truncate(const char *path, off_t length)
630+
{
631+
#ifdef WIN32
632+
int save_errno;
633+
int ret;
634+
int fd;
635+
636+
fd = OpenTransientFile(path, O_RDWR | PG_BINARY);
637+
if (fd >= 0)
638+
{
639+
ret = ftruncate(fd, 0);
640+
save_errno = errno;
641+
CloseTransientFile(fd);
642+
errno = save_errno;
643+
}
644+
else
645+
ret = -1;
646+
647+
return ret;
648+
#else
649+
return truncate(path, length);
650+
#endif
651+
}
625652

626653
/*
627654
* fsync_fname -- fsync a file or directory, handling errors properly

src/backend/storage/smgr/md.c

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -294,19 +294,8 @@ do_truncate(const char *path)
294294
{
295295
int save_errno;
296296
int ret;
297-
int fd;
298297

299-
/* truncate(2) would be easier here, but Windows hasn't got it */
300-
fd = OpenTransientFile(path, O_RDWR | PG_BINARY);
301-
if (fd >= 0)
302-
{
303-
ret = ftruncate(fd, 0);
304-
save_errno = errno;
305-
CloseTransientFile(fd);
306-
errno = save_errno;
307-
}
308-
else
309-
ret = -1;
298+
ret = pg_truncate(path, 0);
310299

311300
/* Log a warning here to avoid repetition in callers. */
312301
if (ret < 0 && errno != ENOENT)

src/include/storage/fd.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@ extern int pg_fsync_no_writethrough(int fd);
153153
extern int pg_fsync_writethrough(int fd);
154154
extern int pg_fdatasync(int fd);
155155
extern void pg_flush_data(int fd, off_t offset, off_t amount);
156+
extern int pg_truncate(const char *path, off_t length);
156157
extern void fsync_fname(const char *fname, bool isdir);
157158
extern int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel);
158159
extern int durable_rename(const char *oldfile, const char *newfile, int loglevel);

0 commit comments

Comments
 (0)