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.
This commit is contained in:
Thomas Haller 2022-10-20 11:51:11 +02:00
parent 70417fda9e
commit d98553e9e7
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728

View file

@ -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