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

旧时模样 提交于 2019-11-28 08:36:57

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.

Add an inotify watch on the slave pty and poll on that. You can get an inotify event on open. You can then poll on the inotify file descriptor and the master pty file descriptor. You can get an inotify event for open (IN_OPEN). This will unblock the poll when the slave side is opened.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!