Browse Source

fpgautils: Attempt to use Linux advisory locks on serial devices

Luke Dashjr 12 years ago
parent
commit
85fa905193
2 changed files with 19 additions and 0 deletions
  1. 1 0
      configure.ac
  2. 18 0
      fpgautils.c

+ 1 - 0
configure.ac

@@ -71,6 +71,7 @@ AC_HEADER_STDC
 AC_CHECK_HEADERS(syslog.h)
 AC_CHECK_HEADERS(syslog.h)
 AC_CHECK_HEADERS([sys/epoll.h])
 AC_CHECK_HEADERS([sys/epoll.h])
 AC_CHECK_HEADERS([sys/prctl.h])
 AC_CHECK_HEADERS([sys/prctl.h])
+AC_CHECK_HEADERS([sys/file.h])
 
 
 AC_FUNC_ALLOCA
 AC_FUNC_ALLOCA
 
 

+ 18 - 0
fpgautils.c

@@ -24,6 +24,10 @@
 #include <dirent.h>
 #include <dirent.h>
 #include <string.h>
 #include <string.h>
 
 
+#ifdef HAVE_SYS_FILE_H
+#include <sys/file.h>
+#endif
+
 #ifdef HAVE_LIBUSB
 #ifdef HAVE_LIBUSB
 #include <libusb.h>
 #include <libusb.h>
 #endif
 #endif
@@ -825,6 +829,20 @@ int serial_open(const char *devpath, unsigned long baud, uint8_t timeout, bool p
 
 
 		return -1;
 		return -1;
 	}
 	}
+	
+#if defined(LOCK_EX) && defined(LOCK_NB)
+	if (likely(!flock(fdDev, LOCK_EX | LOCK_NB)))
+		applog(LOG_DEBUG, "Acquired exclusive advisory lock on %s", devpath);
+	else
+	if (errno == EWOULDBLOCK)
+	{
+		applog(LOG_ERR, "%s is already in use by another process", devpath);
+		close(fdDev);
+		return -1;
+	}
+	else
+		applog(LOG_WARNING, "Failed to acquire exclusive lock on %s: %s (ignoring)", devpath, bfg_strerror(errno, BST_ERRNO));
+#endif
 
 
 	struct termios my_termios;
 	struct termios my_termios;