I'm trying to setup a basic server with epoll to handle multiple clients. However, the value of the variable socket
(line 20) is equal to 0
on the first iteration, but it should be 3
(the accept
socket).
The event is well registered, but with a socket value of 0
. I tried with different flags (EPOLLIN
, EPOLLOUT
), but nothing changes.
Here is the main function:
int main(int argc, char **argv)
{
if (argc != 3)
errx(1, "Usage: ./basic_server SERVER_IP SERVER_PORT");
int cnx = prepare_socket(argv[1], argv[2]);
int epoll_instance = epoll_create1(0);
struct epoll_event event = {};
event.events = EPOLLOUT | EPOLLIN;
struct connection_t *queue = NULL;
if (epoll_ctl(epoll_instance, EPOLL_CTL_ADD, cnx, &event) == -1)
errx(1, "Failed to register server");
while (1)
{
struct epoll_event events[MAX_EVENTS];
int events_count = epoll_wait(epoll_instance, events, MAX_EVENTS, -1);
for (int event_idx = 0; event_idx < events_count; event_idx )
{
printf("%d\n", events[event_idx].data.fd);
int socket = events[event_idx].data.fd; // line 20
if (socket == cnx)
queue = accept_client(epoll_instance, socket, queue);
else
communicate(socket, queue);
}
}
return 0;
}
CodePudding user response:
The .data
field of struct epoll_event
is not touched by the operating system, it is merely associated with the fd
you add to your epoll instance and then returned as is when an event occurs. If you want event.data.fd
to be the right file descriptor then you'll have to set it before calling epoll_ctl
:
struct epoll_event event = {};
event.data.fd = cnx; // <-- here
event.events = EPOLLOUT | EPOLLIN;
// ...
int events_count = epoll_wait(epoll_instance, events, MAX_EVENTS, -1);
// Now events[event_idx].data.fd == cnx as it should.