Taken from 1.2 branch of upstream SVN r16938.

--- a/backends/flint_lock.cc	(revision 16937)
+++ b/backends/flint_lock.cc	(revision 16938)
@@ -2,5 +2,5 @@
  * @brief Flint-compatible database locking.
  */
-/* Copyright (C) 2005,2006,2007,2008,2009,2010,2011 Olly Betts
+/* Copyright (C) 2005,2006,2007,2008,2009,2010,2011,2012 Olly Betts
  *
  * This program is free software; you can redistribute it and/or
@@ -134,4 +134,20 @@
 	close(fds[0]);
 
+	// Connect pipe to stdin and stdout.
+	dup2(fds[1], 0);
+	dup2(fds[1], 1);
+
+	// Make sure we don't hang on to open files which may get deleted but
+	// not have their disk space released until we exit.  Close these
+	// before we try to get the lock because if one of them is open on
+	// the lock file then closing it after obtaining the lock would release
+	// the lock, which would be really bad.
+	for (int i = 2; i < lockfd; ++i) {
+	    // Retry on EINTR; just ignore other errors (we'll get
+	    // EBADF if the fd isn't open so that's OK).
+	    while (close(i) < 0 && errno == EINTR) { }
+	}
+	closefrom(lockfd + 1);
+
 	reason why = SUCCESS;
 	{
@@ -160,5 +176,5 @@
 	    // Tell the parent if we got the lock, and if not, why not.
 	    char ch = static_cast<char>(why);
-	    while (write(fds[1], &ch, 1) < 0) {
+	    while (write(1, &ch, 1) < 0) {
 		// EINTR means a signal interrupted us, so retry.
 		// Otherwise we're DOOMED!  The best we can do is just exit
@@ -169,8 +185,4 @@
 	    if (why != SUCCESS) _exit(0);
 	}
-
-	// Connect pipe to stdin and stdout.
-	dup2(fds[1], 0);
-	dup2(fds[1], 1);
 
 	// Make sure we don't block unmount() of partition holding the current
@@ -184,13 +196,4 @@
 	    // gives a warning even if we cast the result to void.
 	}
-
-	// Make sure we don't hang on to open files which may get deleted but
-	// not have their disk space released until we exit.
-	for (int i = 2; i < lockfd; ++i) {
-	    // Retry on EINTR; just ignore other errors (we'll get
-	    // EBADF if the fd isn't open so that's OK).
-	    while (close(i) < 0 && errno == EINTR) { }
-	}
-	closefrom(lockfd + 1);
 
 	// FIXME: use special statically linked helper instead of cat.
