+
+ /*
+ * On POSIX in the default case the file descriptor of a serial port
+ * is not opened exclusively. Therefore the settings of a port are
+ * overwritten if the serial port is opened a second time. Windows
+ * opens all serial ports exclusively.
+ * So the idea is to open the serial ports alike in the exclusive mode.
+ *
+ * ioctl(*, TIOCEXCL) defines the file descriptor as exclusive. So all
+ * further open calls on the serial port will fail.
+ *
+ * There is a race condition if two processes open the same serial
+ * port. None of the processes will notice the exclusive ownership of
+ * the other process because ioctl() doesn't return an error code if
+ * the file descriptor is already marked as exclusive.
+ * This can be solved with flock(). It returns an error if the file
+ * descriptor is already locked by another process.
+ */
+#ifdef HAVE_FLOCK
+ if (flock(port->fd, LOCK_EX | LOCK_NB) < 0)
+ RETURN_FAIL("flock() failed");
+#endif
+
+#ifdef TIOCEXCL
+ /*
+ * Before Linux 3.8 ioctl(*, TIOCEXCL) was not implemented and could
+ * lead to EINVAL or ENOTTY.
+ * These errors aren't fatal and can be ignored.
+ */
+ if (ioctl(port->fd, TIOCEXCL) < 0 && errno != EINVAL && errno != ENOTTY)
+ RETURN_FAIL("ioctl() failed");
+#endif
+