Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking Linux Serial Port

I have an issue that I'm trying to solve regarding the serial port in Linux. I'm able to open, read from, and close the port just fine. However, I want to ensure that I am the only person reading/writing from the port at any given time.

I thought that this was already done for me after I make the open() function call. However, I am able to call open() multiple times on the same port in my program. I can also have two threads which are both reading from the same port simultaneously.

I tried fixing this issue with flock() and I still had the same problem. Is it because both systems calls are coming from the same pid, even though there are different file descriptors involved with each set of opens and reads? For the record, both open() calls do return a valid file descriptor.

As a result, I'm wondering if there's any way that I can remedy by problem. From my program's perspective, it's not a big deal if two calls to open() are successful on the same port since the programmer should be aware of the hilarity that they are causing. However, I just want to be sure that when I open a port, that I am the only process with access to it.

Thanks for the help.

like image 477
It'sPete Avatar asked Jul 31 '13 20:07

It'sPete


1 Answers

In Linux, you can use the TIOCEXCL TTY ioctl to stop other open()s to the device from succeeding (they'll return -1 with errno==EBUSY, device or resource busy). This only works for terminals and serial devices, but it does not rely on advisory locking.

For example:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <fcntl.h>
#include <errno.h>

int open_device(const char *const device)
{
    int descriptor, result;

    if (!device || !*device) {
        errno = EINVAL;
        return -1;
    }

    do {
        descriptor = open(device, O_RDWR | O_NOCTTY);
    } while (descriptor == -1 && errno == EINTR);
    if (descriptor == -1)
        return -1;

    if (ioctl(descriptor, TIOCEXCL)) {
        const int saved_errno = errno;
        do {
            result = close(descriptor);
        } while (result == -1 && errno == EINTR);
        errno = saved_errno;
        return -1;
    }

    return descriptor;
}

Hope this helps.

like image 188
Nominal Animal Avatar answered Oct 05 '22 12:10

Nominal Animal