【问题标题】:tty events in epoll queue after closing fd 0关闭 fd 0 后 epoll 队列中的 tty 事件
【发布时间】:2014-02-14 12:53:13
【问题描述】:

考虑以下情况:

  • 为 fd 0 (stdin) 注册了一个 EPOLLIN 事件
  • 为 fd 0 生成一个 EPOLLIN 事件,并在 epoll 中隐式排队等待读取
  • fd 0 已关闭(并且 EPOLL_CTL_DELeted)调用 epoll_wait()
  • 调用 epoll_wait() 来读取排队的事件

现在:

  • 如果 stdin 是终端,当调用 epoll_wait() 时,会报告第 2 步的 EPOLLIN 事件
  • 如果标准输入不是终端而是管道,则步骤 2 中的 EPOLLIN 事件将报告

为什么 tty 的大小写不同?

测试程序:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>

struct epoll_event event1 = {
    .events = EPOLLIN,
    .data = { .fd = 0}
};

int main(int argc, char **argv)
{
    int epfd = epoll_create(1);
    int rc;
    epoll_ctl(epfd, EPOLL_CTL_ADD, 0, &event1);
    sleep(2); //allow meself time to type false\n
    printf("closing stdin ...\n");
    close(0);
    //even if i remove it explicitly the event will be found in the que after
    epoll_ctl(epfd, EPOLL_CTL_DEL, 0, &event1);
    printf("gathering events ...\n");
    event1.events = 0;
    event1.data.fd = -1;
    rc = epoll_wait(epfd, &event1, 1, 0);
    switch(rc) {
        case 1:
            printf("event received: event=%d on fd %d\n", event1.events, event1.data.fd);
            break;
        case 0:
            printf("no events received");
            break;
        case -1:
            printf("epoll_wait error\n");
            break;
        default:
            printf("weird event count %d\n", rc);
    }

    return 0;
}

从 tty 使用标准输入运行程序:

[root@tinkerbell src]# ./epolltest 
false
closing stdin ...
gathering events ...
event received: event=1 on fd 0
[root@tinkerbell src]# false
[root@tinkerbell src]# 

从管道使用标准输入运行程序:

[root@tinkerbell src]# cat t.sh
#!/bin/bash

echo "bah";
sleep 10;
[root@tinkerbell src]# ./t.sh | ./epolltest 
closing stdin ...
gathering events ...
no events received[root@tinkerbell src]# 

【问题讨论】:

    标签: epoll


    【解决方案1】:

    different question but the answer can be applied here as well

    epoll 捕获的事件来自一个文件*,因为那是 内核处理的抽象。事件确实发生在文件上*和 如果你 dup()ing 1000 次单个 fd,就没有办法这么说 事件适用于 fd = 122。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      相关资源
      最近更新 更多