[Libguestfs] [PATCH v6 06/41] common/cleanups: Add CLEANUP_CLOSE function.

Richard W.M. Jones
Thu, 15 Jun 2017 17:05:56 -0000

This is present in the daemon, but the function could be used
throughout the code.
---
 common/cleanups/cleanups.h        | 4 ++++
 common/cleanups/stdlib-cleanups.c | 9 +++++++++
 2 files changed, 13 insertions(+)

diff --git a/common/cleanups/cleanups.h b/common/cleanups/cleanups.h
index 211bce98a..70021e94e 100644
--- a/common/cleanups/cleanups.h
+++ b/common/cleanups/cleanups.h
@@ -26,6 +26,8 @@
   __attribute__((cleanup(guestfs_int_cleanup_hash_free)))
 #define CLEANUP_UNLINK_FREE                                     \
   __attribute__((cleanup(guestfs_int_cleanup_unlink_free)))
+#define CLEANUP_CLOSE                                  \
+  __attribute__((cleanup(guestfs_int_cleanup_close)))
 #define CLEANUP_FCLOSE                                  \
   __attribute__((cleanup(guestfs_int_cleanup_fclose)))
 #define CLEANUP_PCLOSE                                  \
@@ -48,6 +50,7 @@
 #define CLEANUP_FREE
 #define CLEANUP_HASH_FREE
 #define CLEANUP_UNLINK_FREE
+#define CLEANUP_CLOSE
 #define CLEANUP_FCLOSE
 #define CLEANUP_PCLOSE
 #define CLEANUP_XMLFREE
@@ -65,6 +68,7 @@
 extern void guestfs_int_cleanup_free (void *ptr);
 extern void guestfs_int_cleanup_hash_free (void *ptr);
 extern void guestfs_int_cleanup_unlink_free (char **ptr);
+extern void guestfs_int_cleanup_close (void *ptr);
 extern void guestfs_int_cleanup_fclose (void *ptr);
 extern void guestfs_int_cleanup_pclose (void *ptr);
 extern void guestfs_int_cleanup_xmlFree (void *ptr);
diff --git a/common/cleanups/stdlib-cleanups.c
b/common/cleanups/stdlib-cleanups.c
index 0512a86a2..e77708db4 100644
--- a/common/cleanups/stdlib-cleanups.c
+++ b/common/cleanups/stdlib-cleanups.c
@@ -83,6 +83,15 @@ guestfs_int_cleanup_unlink_free (char **ptr)
 }

 void
+guestfs_int_cleanup_close (void *ptr)
+{
+  const int fd = * (int *) ptr;
+
+  if (fd >= 0)
+    close (fd);
+}
+
+void
 guestfs_int_cleanup_fclose (void *ptr)
 {
   FILE *f = * (FILE **) ptr;
--
2.13.0