开发者

epoll: Distinguishing "listener" FDs

开发者 https://www.devze.com 2023-01-04 20:26 出处:网络
How can I distinguish between \"listener\" file descriptors and \"client\" file descriptors? Here\'s what I saw in the manpage example:

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消