【问题标题】:Non blocking pseudo terminal, recovery after POLLHUP非阻塞伪终端,POLLHUP 后恢复
【发布时间】:2021-05-12 06:24:48
【问题描述】:

我通过使用open() 函数和O_RDWR | O_NOCTTY | O_NONBLOCK 标志打开/dev/ptmx 创建一个新的伪终端。然后我使用poll()函数等待来自远端的传入数据:

struct pollfd pollFileDescriptors[numberOfTerminals];
for (unsigned terminalIndex = 0; terminalIndex < numberOfTerminals; terminalIndex++) {
    pollFileDescriptors[terminalIndex].fd = terminals[terminalIndex].getFileDescriptor();
    pollFileDescriptors[terminalIndex].events = POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND;
}

int ready = poll(pollFileDescriptors, terminals.getNumberOfTerminals(), timeoutMSec);

在远端关闭连接之前,一切都像做梦一样。在这种情况下,poll() 函数始终返回 POLLHUP revents 标志。这是设计使然,但是我该怎么做才能使其像以前一样运行,即等待另一个进程打开并使用伪终端。我的意思是它会等待,但会立即返回并设置POLLHUP。另一方面,如果我关闭文件描述符,我无法保证收到与重新打开/dev/ptmx 后相同的伪终端ID。有什么办法可以去掉POLLHUP revents 标志?

我发现了一个类似的问题:Poll() on Named Pipe returns with POLLHUP constantly and immediately,但是我已经按照那里的描述使用了 O_RDWR,但它在命名管道的情况下没有帮助。

【问题讨论】:

    标签: c++ linux pty


    【解决方案1】:

    创建后立即重新打开伪终端即可轻松解决此问题。只要至少有一位作家存在,POLLHUP 就不会出现,因此我们可以通过 open()ptsname() 自己完成此操作:

    // Create a new pseudo terminal
    int fileDescriptor = open("/dev/ptmx", O_RDWR | O_NOCTTY | O_NONBLOCK);
    grantpt(fileDescriptor);
    unlockpt(fileDescriptor);
    
    // Reopen it for write
    const char *targetPath = ptsname(fileDescriptor);
    int dummyWriterFileDescriptor = open(fileName.c_str(), O_WRONLY | O_NOCTTY | O_NONBLOCK);
    

    【讨论】:

      猜你喜欢
      • 2014-11-26
      • 2017-04-18
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2015-11-27
      相关资源
      最近更新 更多