commit:     a91a402d9c987034cbaec2490e11334f94102e6c
Author:     Michał Górny <mgorny <AT> gentoo <DOT> org>
AuthorDate: Sat Nov 22 20:01:48 2025 +0000
Commit:     Michał Górny <mgorny <AT> gentoo <DOT> org>
CommitDate: Sat Nov 22 20:02:11 2025 +0000
URL:        https://gitweb.gentoo.org/proj/steve.git/commit/?id=a91a402d

Add a trivial fd guard class

Signed-off-by: Michał Górny <mgorny <AT> gentoo.org>

 steve.cxx | 13 ++++++-------
 1 file changed, 6 insertions(+), 7 deletions(-)

diff --git a/steve.cxx b/steve.cxx
index d666f5c..aeff215 100644
--- a/steve.cxx
+++ b/steve.cxx
@@ -332,6 +332,11 @@ static const struct option steve_opts[] = {
        { 0 },
 };
 
+struct fd_guard {
+       int fd;
+       ~fd_guard() { close(fd); }
+};
+
 int main(int argc, char **argv)
 {
        steve_state state = { 0 };
@@ -383,6 +388,7 @@ int main(int argc, char **argv)
                perror("unable to open /dev/cuse");
                return 1;
        }
+       fd_guard cuse_fd_guard{cuse_fd};
 
        const char *dev_name = "DEVNAME=steve";
        const char *dev_info_argv[] = { dev_name };
@@ -403,7 +409,6 @@ int main(int argc, char **argv)
                cuse_lowlevel_new(args_ptr.get(), &ci, &steve_ops, &state), 
fuse_session_destroy};
        if (!session) {
                fprintf(stderr, "failed to initialize FUSE");
-               close(cuse_fd);
                return 1;
        }
 
@@ -411,12 +416,10 @@ int main(int argc, char **argv)
                cuse_event{event_new(evb.get(), cuse_fd, EV_READ|EV_PERSIST, 
steve_handle_cuse, session.get()), event_free};
        if (!cuse_event) {
                fprintf(stderr, "failed to initialize CUSE handler");
-               close(cuse_fd);
                return 1;
        }
        if (event_add(cuse_event.get(), nullptr) == -1) {
                fprintf(stderr, "failed to enable CUSE handler");
-               close(cuse_fd);
                return 1;
        }
 
@@ -424,24 +427,20 @@ int main(int argc, char **argv)
                sigusr1_event{evsignal_new(evb.get(), SIGUSR1, 
steve_handle_sigusr1, &state), event_free};
        if (!sigusr1_event) {
                fprintf(stderr, "failed to initialize SIGUSR1 handler");
-               close(cuse_fd);
                return 1;
        }
        if (event_add(sigusr1_event.get(), nullptr) == -1) {
                fprintf(stderr, "failed to enable SIGUSR1 handler");
-               close(cuse_fd);
                return 1;
        }
 
        std::string mountpoint = "/dev/fd/" + std::to_string(cuse_fd);
        if (fuse_session_mount(session.get(), mountpoint.c_str()) == -1) {
                fprintf(stderr, "failed to mount the filesystem");
-               close(cuse_fd);
                return 1;
        }
 
        event_base_dispatch(evb.get());
        fuse_session_unmount(session.get());
-       close(cuse_fd);
        return 0;
 }

Reply via email to