From 8e34cdbf453a70e720913c6346ece19598c3ba54 Mon Sep 17 00:00:00 2001 From: waker Date: Tue, 22 May 2012 22:17:11 +0200 Subject: atomic config writing --- conf.c | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) (limited to 'conf.c') diff --git a/conf.c b/conf.c index d4e0ee28..eff15de5 100644 --- a/conf.c +++ b/conf.c @@ -15,11 +15,19 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . */ +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif #include #include #include #include #include +#include +#include +#if HAVE_SYS_SYSLIMITS_H +#include +#endif #include "conf.h" #include "threading.h" @@ -107,19 +115,33 @@ conf_load (void) { int conf_save (void) { extern char dbconfdir[1024]; // $HOME/.config/deadbeef - char str[1024]; - snprintf (str, 1024, "%s/config", dbconfdir); - FILE *fp = fopen (str, "w+t"); + + char tempfile[PATH_MAX]; + snprintf (tempfile, sizeof (tempfile), "%s/config.tmp", dbconfdir); + + char str[PATH_MAX]; + snprintf (str, sizeof (str), "%s/config", dbconfdir); + + FILE *fp = fopen (tempfile, "w+t"); if (!fp) { fprintf (stderr, "failed to open config file for writing\n"); return -1; } conf_lock (); for (DB_conf_item_t *it = conf_items; it; it = it->next) { - fprintf (fp, "%s %s\n", it->key, it->value); + if (fprintf (fp, "%s %s\n", it->key, it->value) < 0) { + fprintf (stderr, "failed to write to file %s (%s)\n", tempfile, strerror (errno)); + fclose (fp); + conf_unlock (); + return -1; + } } fclose (fp); conf_unlock (); + int err = rename (tempfile, str); + if (err != 0) { + fprintf (stderr, "config rename %s -> %s failed: %s\n", tempfile, str, strerror (errno)); + } return 0; } -- cgit v1.2.3