Locking Linux Serial Port

前端 未结 2 1000
庸人自扰
庸人自扰 2021-01-06 03:08

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

相关标签:
2条回答
  • 2021-01-06 03:16

    I was able to fix the issue with use of the flock() function. Use of the structure and fcntl() wasn't working for me for some reason. With use of flock() I was able to add two lines of code and solve my issue.

    0 讨论(0)
  • 2021-01-06 03:33

    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.

    0 讨论(0)
提交回复
热议问题