[glib/th/gspawn-no-safe-close: 3/4] gutilsprivate: add safe_close() and safe_close_with_error() helper




commit 6dce7292a6b3f8a2bafe0d2f9f3b8ce90f1693a7
Author: Thomas Haller <thaller redhat com>
Date:   Tue Oct 18 08:42:08 2022 +0200

    gutilsprivate: add safe_close() and safe_close_with_error() helper

 glib/gutils.c        | 29 +++++++++++++++++++++++++++++
 glib/gutilsprivate.h |  2 ++
 2 files changed, 31 insertions(+)
---
diff --git a/glib/gutils.c b/glib/gutils.c
index 78ccd61214..4ad92da584 100644
--- a/glib/gutils.c
+++ b/glib/gutils.c
@@ -3246,3 +3246,32 @@ g_abort (void)
   ExitProcess (127);
 }
 #endif
+
+/**
+ * _g_safe_close:
+ * fd: the file descriptor to close.
+ *
+ * This is a safe wrapper around g_close() and close(). From internal code,
+ * in almost all cases this function should be used instead of g_close()
+ * and close().
+ *
+ * This is guaranteed to be async-signal-safe (except assertion failures), so it
+ * can be used from a signal handler or between fork and exec.
+ *
+ * As `man 2 close` documents, there isn't much you can do about errors anyway.
+ * _g_safe_close() enforces this by returning no result.
+ *
+ * The function preserves errno.
+ *
+ * This function just calls g_close(), so it handles EINTR (currently by ignoring
+ * it) and EBADF (by asserting).
+ */
+void
+_g_safe_close (int fd)
+{
+  int errsv;
+
+  errsv = errno;
+  g_close (fd, NULL);
+  errno = errsv;
+}
diff --git a/glib/gutilsprivate.h b/glib/gutilsprivate.h
index 77bed4e87b..2359cf0794 100644
--- a/glib/gutilsprivate.h
+++ b/glib/gutilsprivate.h
@@ -54,6 +54,8 @@ g_nearest_pow (gsize num)
   return n + 1;
 }
 
+void _g_safe_close (int fd);
+
 G_END_DECLS
 
 #endif /* __G_UTILS_PRIVATE_H__ */


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]