Repository: serialport/serialport-rs (language: rust)

Issue:
Lock serial port under Linux
This issue was migrated from GitLab. The original issue can be found here:
https://gitlab.com/susurrus/serialport-rs/-/issues/109
---
In Linux, use `flock(fd, LOCK_EX | LOCK_NB)` to lock the serial port.

See

* [What is the best practice for locking serial ports and other devices in Linux?](https://stackoverflow.com/questions/30316722/what-is-the-best-practice-for-locking-serial-ports-and-other-devices-in-linux) — StackOverflow.
* [Function `nix::fcntl::flock`](https://docs.rs/nix/0.20.0/nix/fcntl/fn.flock.html)


Discussion / hints:

Fix patch:
diff --git a/src/posix/tty.rs b/src/posix/tty.rs
index 00a4863d..0d3a1879 100644
--- a/src/posix/tty.rs
+++ b/src/posix/tty.rs
@@ -105,6 +105,11 @@ impl TTYPort {
             nix::sys::stat::Mode::empty(),
         )?);
 
+        // Try to claim exclusive access to the port. This is performed even
+        // if the port will later be set as non-exclusive, in order to respect
+        // other applications that may have an exclusive port lock.
+        ioctl::tiocexcl(fd.0)?;
+
         let mut termios = MaybeUninit::uninit();
         nix::errno::Errno::result(unsafe { tcgetattr(fd.0, termios.as_mut_ptr()) })?;
         let mut termios = unsafe { termios.assume_init() };
@@ -156,7 +161,7 @@ impl TTYPort {
         Ok(TTYPort {
             fd: fd.into_raw(),
             timeout: builder.timeout,
-            exclusive: false,
+            exclusive: true,
             port_name: Some(builder.path.clone()),
             #[cfg(any(target_os = "ios", target_os = "macos"))]
             baud_rate: builder.baud_rate,


Test patch: