From 57f826ce6f8c83a0227630284dc4673f61b459af Mon Sep 17 00:00:00 2001
From: Alberto Bertogli <albertito@blitiri.com.ar>
Date: Thu, 24 Sep 2009 20:45:28 -0300
Subject: [PATCH 02/15] jfsck(): Lock the file before operating on it

Callers of jfsck() must not call it when the file is in use. However, it
doesn't hurt to protect from it by locking the file before using it, to
protect unwary users. The close() takes care of the unlock.

Note that if the process has locks held on the file, it's already in
trouble because it will loose them anyway as we're re-opening and closing
the file, so this patch does not change that situation.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
---
 libjio/check.c |   11 +++++++++++
 1 files changed, 11 insertions(+), 0 deletions(-)

diff --git a/libjio/check.c b/libjio/check.c
index f3e37e2..4afb9e3 100644
--- a/libjio/check.c
+++ b/libjio/check.c
@@ -123,6 +123,17 @@ enum jfsck_return jfsck(const char *name, const char *jdir,
 
 	fs.name = (char *) name;
 
+	/* Locking the whole file protect us from concurrent runs, but it's
+	 * not to be trusted nor assumed (lingering transactions break it): it
+	 * just helps prevent some accidents. */
+	lr = plockf(fs.fd, F_LOCKW, 0, 0);
+	if (lr == -1) {
+		/* In the future, we may want to differentiate this case from
+		 * a normal I/O error. */
+		ret = J_EIO;
+		goto exit;
+	}
+
 	if (jdir == NULL) {
 		fs.jdir = (char *) malloc(PATH_MAX);
 		if (fs.jdir == NULL) {
-- 
1.6.2.2.646.gb214

