How can I detect when someone opens the slave side of a pty (pseudo-terminal) in Linux?

后端 未结 2 1111
悲&欢浪女
悲&欢浪女 2020-12-09 12:10

Having more than one process read from a serial device (/dev/ttyXX) makes it so that both processes can\'t get all of the data -- the data will be split between them in some

2条回答
  •  庸人自扰
    2020-12-09 12:56

    The reason you can't find this is because there's no documented interface specifically to allow it. However, there is a trick that allows you to do it. After opening the pseudo-terminal master (assumed here to be file descriptor ptm), you open and immediately close the slave side:

    close(open(ptsname(ptm), O_RDWR | O_NOCTTY));
    

    This sets the HUP flag on the tty master. You now poll the HUP flag regularly with poll() (say, whenever data comes in from your data source):

    struct pollfd pfd = { .fd = ptm, .events = POLLHUP };
    poll(&pfd, 1, 10 /* or other small timeout */);
    
    if (!(pfd.revents & POLLHUP))
    {
        /* There is now a reader on the slave side */
    }
    

    If the reader ever goes away, POLLHUP will be set again.

    In your case, you probably don't even need to remember from one loop to the next whether a given pty has a reader - just block on read() on your data source, then when data is available, simultaneously poll() all of your master ttys and send the data to any of them that do not have POLLHUP set.

提交回复
热议问题