diff options
author | Thomas Haller <thaller@redhat.com> | 2022-10-20 11:51:11 +0200 |
---|---|---|
committer | Thomas Haller <thaller@redhat.com> | 2022-10-25 13:12:49 +0200 |
commit | d98553e9e78bc3a1fd997caeb3cf92cded7b775a (patch) | |
tree | 5b6d3e307d3fd360e0280f83e4ca083399b88d8a | |
parent | 70417fda9ec601327ff654400ffcac9fce6c93e0 (diff) |
main: use helper function to write pid file in nm_main_utils_write_pidfile()
On the surface, writing a file seams simple enough. But there are many
pitfalls:
- we should retry on EINTR.
- we should check for incomplete writes and loop.
- we possibly should check errors from close.
- we possibly should write to a temporary file and do atomic rename.
Use nm_utils_file_set_contents() to get this right.
-rw-r--r-- | src/core/main-utils.c | 28 |
1 files changed, 7 insertions, 21 deletions
diff --git a/src/core/main-utils.c b/src/core/main-utils.c index b18ae311ed..c6fa05c0ca 100644 --- a/src/core/main-utils.c +++ b/src/core/main-utils.c @@ -18,6 +18,7 @@ #include "main-utils.h" #include "NetworkManagerUtils.h" #include "nm-config.h" +#include "libnm-glib-aux/nm-io-utils.h" static gboolean sighup_handler(gpointer user_data) @@ -76,31 +77,16 @@ nm_main_utils_setup_signals(GMainLoop *main_loop) gboolean nm_main_utils_write_pidfile(const char *pidfile) { - char pid[16]; - int fd; - int errsv; - gboolean success = FALSE; - int r; + gs_free_error GError *error = NULL; + char pid[16]; - if ((fd = open(pidfile, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 00644)) < 0) { - errsv = errno; - fprintf(stderr, _("Opening %s failed: %s\n"), pidfile, nm_strerror_native(errsv)); + nm_sprintf_buf(pid, "%lld", (long long) getpid()); + if (!nm_utils_file_set_contents(pidfile, pid, -1, 00644, NULL, NULL, &error)) { + fprintf(stderr, _("Writing to %s failed: %s\n"), pidfile, error->message); return FALSE; } - g_snprintf(pid, sizeof(pid), "%d", getpid()); - if (write(fd, pid, strlen(pid)) < 0) { - errsv = errno; - fprintf(stderr, _("Writing to %s failed: %s\n"), pidfile, nm_strerror_native(errsv)); - } else - success = TRUE; - - r = nm_close_with_error(fd); - if (r < 0) { - fprintf(stderr, _("Closing %s failed: %s\n"), pidfile, nm_strerror_native(-r)); - } - - return success; + return TRUE; } void |