From cbd1cffa3eb9e6e5ca82ec67d3c4211a019dd1ed Mon Sep 17 00:00:00 2001 From: Jim Meyering Date: Sat, 4 Aug 2012 11:02:40 +0200 Subject: [PATCH] truncate: don't leak a file descriptor with --ref=PIPE MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit * src/truncate.c (main): For a user who makes the mistake of using a non-seekable file as a reference for the desired length, truncate would open that file, attempt to seek to its end, but upon seek failure would neglect to close the file descriptor. Close the file descriptor even when lseek fails. In addition, ignore failure to close that reference FD, since as long as the lseek succeeds, a close failure doesn't matter. Coverity spotted the potential FD leak. Improved-by: Pádraig Brady. --- src/truncate.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/truncate.c b/src/truncate.c index c1e9666174..d638993d6e 100644 --- a/src/truncate.c +++ b/src/truncate.c @@ -370,8 +370,15 @@ main (int argc, char **argv) if (0 <= ref_fd) { off_t file_end = lseek (ref_fd, 0, SEEK_END); - if (0 <= file_end && close (ref_fd) == 0) + int saved_errno = errno; + close (ref_fd); /* ignore failure */ + if (0 <= file_end) file_size = file_end; + else + { + /* restore, in case close clobbered it. */ + errno = saved_errno; + } } } if (file_size < 0) -- 2.47.2