Skip to content

unix: Use flock to ensure exclusive access #266

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

Tiwalun
Copy link

@Tiwalun Tiwalun commented May 14, 2025

Some applications, e.g. picocom, use flock to ensure exclusive access to the serial port, but don't seem to use the tiocexcl ioctl. This means that, without using flock, it is currently possible to connect to a port using picocom first, and then connect using this crate. This leads to problem where not all data is received by the Rust application.

To avoid this, flock can be used to acquire an advisory lock on the port. This will prevent this crate from opening the port when it has already been opened by picocom. Note that the lock is only advisory, meaning that this requires collaboration between applications.

Fixes #265.

@@ -130,6 +167,9 @@ impl TTYPort {
// other applications that may have an exclusive port lock.
ioctl::tiocexcl(fd.0)?;

// Also use flock to lock the port
flock_exclusive(fd.0)?;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After sleeping over it: Shouldn't we make this a "all or nothing" operation and attempt to gracefully retreat from this situation an not leave a port locked in the one way or the other?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but that is what should be happening already. If the flock fails, then an error will be returned, and the serial port is not opened.

If the call to ioctl::tiocexcl fails, then we never get to the point where flock is called.

The lock placed by flock will be removed automatically when the file descriptor is closed, according to its man page.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. I should add a note on that for future me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Use flock for exclusive serial port access on Linux
2 participants