]> granicus.if.org Git - libevent/commitdiff
Simplify and correct evutil_open_closeonexec_
authorNick Mathewson <nickm@torproject.org>
Mon, 25 Jun 2012 16:19:26 +0000 (12:19 -0400)
committerNick Mathewson <nickm@torproject.org>
Mon, 25 Jun 2012 16:19:26 +0000 (12:19 -0400)
The original code needlessly called open in its two- or three-
argument format depending on the O_CREAT flag; this should not be
needed.

The code also leaked an fd if fcntl() failed.

Reported by Dave Hart.

evutil.c

index bc4ee99e31d6f643a012ca8040ed7551d8e9f3bf..352649f718224aa9ee1b54a6fe901ec7b97e66c2 100644 (file)
--- a/evutil.c
+++ b/evutil.c
@@ -99,24 +99,20 @@ evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode)
        int fd;
 
 #ifdef O_CLOEXEC
-       if (flags & O_CREAT)
-               fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode);
-       else
-               fd = open(pathname, flags|O_CLOEXEC);
+       fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode);
        if (fd >= 0 || errno == EINVAL)
                return fd;
        /* If we got an EINVAL, fall through and try without O_CLOEXEC */
 #endif
-       if (flags & O_CREAT)
-               fd = open(pathname, flags, (mode_t)mode);
-       else
-               fd = open(pathname, flags);
+       fd = open(pathname, flags, (mode_t)mode);
        if (fd < 0)
                return -1;
 
 #if defined(FD_CLOEXEC)
-       if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
+       if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
+               close(fd);
                return -1;
+       }
 #endif
 
        return fd;