epoll:区分“监听者” FD

发布于 2024-09-07 08:01:35 字数 300 浏览 6 评论 0原文

如何区分“侦听器”文件描述符和“客户端”文件描述符?

这是我在 manpage 示例中看到的内容:

if(events[n].data.fd == listener) {
    ...
} else {
    ...
}

'但是如果我没有怎么办访问监听器

抱歉,如果这是一个模糊的问题。我不太确定如何措辞。

How can I distinguish between "listener" file descriptors and "client" file descriptors?

Here's what I saw in the manpage example:

if(events[n].data.fd == listener) {
    ...
} else {
    ...
}

'But what if I don't have access to listener?

Sorry if this is a vague question. I'm not quite sure how to word it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情场扛把子 2024-09-14 08:01:35

假设您正在编写一个服务器,您应该将侦听套接字描述符保留在某个变量中(手册页中的listener),或者为您提供给epoll_ctl(的每个套接字)设置一个小结构2) 并使用 struct epoll_eventdata.ptr 成员指向它(不要忘记在套接字关闭时取消分配该结构)。

像这样的事情:

struct socket_ctl
{
    int fd;    /* socket descriptor */
    int flags; /* my info about the socket, say (flags&1) != 0 means server */
    /* whatever else you want to have here, like pointers to buffers, etc. */
};
...
struct socket_ctl* pctl = malloc( sizeof( struct socket_ctl ));
/* check for NULL */
pctl->fd = fd;
pctl->flags = 1; /* or better some enum or define */
struct epoll_event ev;
ev.events = EPOLLIN|...;
ev.data.ptr = pctl;
...
if (( events[n].data.ptr->flags & 1 ) != 0 )
{
    /* this is server socket */
}

正如您所看到的,它比仅仅访问服务器套接字描述符要做更多的工作,但它有一个很好的特性,可以将与一个套接字相关的所有信息保存在一处。

Assuming you are writing a server, you should either keep the listening socket descriptor around in some variable (listener in the manual page), or setup a small structure for each socket you give to epoll_ctl(2) and point to it with data.ptr member of the struct epoll_event (don't forget to de-allocate that structure when socket is closed).

Something like this:

struct socket_ctl
{
    int fd;    /* socket descriptor */
    int flags; /* my info about the socket, say (flags&1) != 0 means server */
    /* whatever else you want to have here, like pointers to buffers, etc. */
};
...
struct socket_ctl* pctl = malloc( sizeof( struct socket_ctl ));
/* check for NULL */
pctl->fd = fd;
pctl->flags = 1; /* or better some enum or define */
struct epoll_event ev;
ev.events = EPOLLIN|...;
ev.data.ptr = pctl;
...
if (( events[n].data.ptr->flags & 1 ) != 0 )
{
    /* this is server socket */
}

As you can see it's much more work then just having access to the server socket descriptor, but it has a nice property of keeping all information related to one socket in one place.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文