Search code examples
clinuxconcurrencyserial-porttty

open tty from multiple processes simultaneously possible?


I have to ensure that a tty device on linux is only accessible from one instance at once. To do so, I have implemented a flock() function. However, in my tests I wasnt able to open the serial port from another process at the same time even without the flock() logic.

Im now wondering if this is the normal behaviour in all cases so I can delete my flock() logic and rely on the blocking open() logic? Is it in any case possible to open a serial port from different instances simultaneously?

EDIT:

I have figured out that it is indeed possible to open the tty port multiple times simultaneously without flock() logic. However, it seems, that the open() function is blocked due to the flock().


Solution

  • Normally, it is possible to open a serial device from more than one process simultaneously.

    You can use the TIOCEXCL ioctl() to get exclusive access:

    if (!ioctl(fd, TIOCEXCL)) {
        /* Any further open() on the tty
           that is currently open on descriptor fd
           will fail with errno == EBUSY
           (except for the administrator, with the 
            CAP_SYS_ADMIN capability) */
    }
    

    and to re-allow other open()s,

    ioctl(fd, TIOCNXCL);
    

    You'll need to include <sys/ioctl.h> for the function, and <termios.h> for the constants.

    Many Linux serial libraries already do this. Some serial drivers may allow only one open at a time, too, so to determine the reason for the behaviour you are seeing, I'd need a lot more details (how you open the serial device, and the serial device driver used, in particular).

    Personally -- and I do believe this is what most Linux serial libraries do --, I recommend you try the ioctl(fd, TIOCEXCL), and maybe warn the user if it fails (it returns 0 if success, -1 otherwise); and, in all cases, use ioctl(fd, TIOCNXCL); close(fd); to close the tty.