changeset 22269:b553f6960cb9

lib: Add file_lock_set_unlink_on_free()
author Timo Sirainen <timo.sirainen@dovecot.fi>
date Thu, 22 Jun 2017 01:47:51 +0300
parents 382ee00c9669
children 5b108ca20b05
files src/lib/file-lock.c src/lib/file-lock.h
diffstat 2 files changed, 17 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/src/lib/file-lock.c	Thu Jun 22 10:35:16 2017 +0300
+++ b/src/lib/file-lock.c	Thu Jun 22 01:47:51 2017 +0300
@@ -18,6 +18,7 @@
 	struct timeval locked_time;
 	int lock_type;
 	enum file_lock_method lock_method;
+	bool unlink_on_free;
 };
 
 static struct timeval lock_wait_start;
@@ -340,6 +341,11 @@
 	return 1;
 }
 
+void file_lock_set_unlink_on_free(struct file_lock *lock, bool set)
+{
+	lock->unlink_on_free = set;
+}
+
 void file_unlock(struct file_lock **_lock)
 {
 	struct file_lock *lock = *_lock;
@@ -347,6 +353,11 @@
 
 	*_lock = NULL;
 
+	/* unlocking is unnecessary when the file is unlinked. or alternatively
+	   the unlink() must be done before unlocking, because otherwise it
+	   could be deleting the new lock. */
+	i_assert(!lock->unlink_on_free);
+
 	if (file_lock_do(lock->fd, lock->path, F_UNLCK,
 			 lock->lock_method, 0, &error) == 0) {
 		/* this shouldn't happen */
@@ -362,6 +373,9 @@
 
 	*_lock = NULL;
 
+	if (lock->unlink_on_free)
+		i_unlink(lock->path);
+
 	file_lock_log_warning_if_slow(lock);
 	i_free(lock->path);
 	i_free(lock);
--- a/src/lib/file-lock.h	Thu Jun 22 10:35:16 2017 +0300
+++ b/src/lib/file-lock.h	Thu Jun 22 01:47:51 2017 +0300
@@ -45,6 +45,9 @@
 /* Change the lock type. WARNING: This isn't an atomic operation!
    The result is the same as file_unlock() + file_try_lock(). */
 int file_lock_try_update(struct file_lock *lock, int lock_type);
+/* When the lock is freed, unlink() the file automatically. This can be useful
+   for files that are only created to exist as lock files. */
+void file_lock_set_unlink_on_free(struct file_lock *lock, bool set);
 
 /* Unlock and free the lock. */
 void file_unlock(struct file_lock **lock);