3

I am finding a difference in the implementation of SerialPort.Open() between Windows and Mono on Ubuntu. Here is my current implementation:

        if (serPort.IsOpen)
        {
            serPort.Close();
        }

        serPort.BaudRate = Convert.ToInt32(baudRateCmbBox.Text);
        serPort.PortName = serPortCmbBox.Text;

        try
        {
            serPort.Open();
        }
        catch
        {
            return false;
        }

        return true;

In Windows, if I have another program with the same serial port open, then an exception is thrown and the function returns false. However, in Mono, the serial port still gets opened, regardless of whether or not another program already has the serial port open. It even reads and writes to the serial port at the same time as the other program.

So the question is, is there a way that will work both in Windows and in Mono that will allow me to check if another program already has the serial port open?

1

1 Answer 1

2

In POSIX this behaviour is due to different file locking semantics: many processes can access the same file. If you'd run your code on Mono on Windows, you would see the same behaviour as Microsoft .Net is showing.

To work in the same way on Linux, open_serial() method in Mono native helper would have to acquire flock() on the opened file descriptor.

Sign up to request clarification or add additional context in comments.

5 Comments

Do you know of any built-in C# functionality that would accomplish this? I'd rather not have to use non-C# code (or other people's code) if I can avoid it.
File a bug report with Mono - although SerialPort is so rarely used that you would probably have to implement the runtime fixes yourself. That's what I wound up doing, anyway.
Actually, using flock() won't help. On Linux lock is obtained by creation of special file (usually sth like /var/tmp/LCK..ttyS0). And this is what applications like minicom or gtkterm are using. Mac has its own way. Nevertheless it could be done - and will be if I find enough time and someone with Mac to test.
@konrad.kruczynski See: What is the best practice for locking serial ports and other devices in Linux? It seems flock() should be used going forward.
@CraigMcQueen Interesting, thank you! For me this is also the cleaner approach so I'm glad the other one is being deprecated now. Nevertheless I haven't done any work on this yet, but who knows - and I even possess an OS X now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.