diff mbox

[LEDE-DEV,uci] file: use fsync after renaming temp file

Message ID 20160907061103.11873-1-zajec5@gmail.com
State Changes Requested
Headers show

Commit Message

Rafał Miłecki Sept. 7, 2016, 6:11 a.m. UTC
From: Rafał Miłecki <rafal@milecki.pl>

We already use a temp file and rename it to avoid ending up with an
empty file e.g. on power cut. What was missing however is fsync after
rename. It's required to make sure directory starts using the new file
instead of the old one.

With this patch UCI changes are stored correctly even with power cut
immediatelly following UCI commit.

Signed-off-by: Rafał Miłecki <rafal@milecki.pl>
---
 file.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

Comments

Vittorio Gambaletta Sept. 8, 2016, 12:21 a.m. UTC | #1
Hi,

On 07/09/2016 08:11:03 CEST, Rafał Miłecki wrote:
> +		dir_fd = open(dirname(path), O_RDONLY);
> +		if (dir_fd) {

This should be dir_fd != -1, as -1 is returned when an error occurs in open().

> +			fsync(dir_fd);
> +			close(dir_fd);
> +		}

Cheers,
Vittorio
diff mbox

Patch

diff --git a/file.c b/file.c
index 7e1e4e6..86d9032 100644
--- a/file.c
+++ b/file.c
@@ -23,6 +23,7 @@ 
 #include <stdbool.h>
 #include <unistd.h>
 #include <fcntl.h>
+#include <libgen.h>
 #include <stdio.h>
 #include <ctype.h>
 #include <glob.h>
@@ -801,11 +802,20 @@  done:
 	free(path);
 	uci_close_stream(f1);
 	if (do_rename) {
+		int dir_fd;
+
 		path = realpath(p->path, NULL);
 		if (!path || rename(filename, path)) {
 			unlink(filename);
 			UCI_THROW(ctx, UCI_ERR_IO);
 		}
+
+		dir_fd = open(dirname(path), O_RDONLY);
+		if (dir_fd) {
+			fsync(dir_fd);
+			close(dir_fd);
+		}
+
 		free(path);
 	}
 	free(filename);