Here is a minimal example code:
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <stdio.h>
#include <stdlib.h>
#define NPROTO 10000
#define LOCALHOST "127.0.0.1"
/* */
int main(int argc, char *argv[])
{
int sfd, epfd;
struct sockaddr_in so_address;
struct epoll_event ev, evs[1];
sfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
if(sfd < 0){
fprintf(stderr, "socket() failed\n");
exit(1);
}
epfd = epoll_create(1);
if(epfd < 0){
fprintf(stderr, "socket() failed\n");
exit(1);
}
memset(&so_address, 0, sizeof(so_address));
so_address.sin_family = AF_INET;
so_address.sin_port = htons(NPROTO);
if(1 != inet_pton(AF_INET, LOCALHOST, (struct in_addr*)(&so_address.sin_addr.s_addr))){
fprintf(stderr, "inet_pton() failed\n");
exit(1);
}
if(bind(sfd, (struct sockaddr *)&so_address, sizeof(so_address)) < 0){
fprintf(stderr, "bind() failed\n");
exit(1);
}
if(listen(sfd, 4) < 0){
fprintf(stderr, "listen() failed\n");
exit(1);
}
ev.data.fd = sfd;
ev.events = 0;
epoll_ctl(epfd, EPOLL_CTL_ADD, sfd, &ev);
epoll_wait(epfd, evs, 1, -1);
return 0;
}
The code creates socket that listens for the connections and registers the socket with an epoll
set. Last lines wait for the activity on a epoll set.
Note that events
flags of a struct epoll_event
is set to zero
. With the above example code, telnet
connects to the program. If I change the flags to EPOLLIN
, telnet
reports "Connection refused".
The question is, why telnet
connects whithout an accept being called?
CodePudding user response:
Because the port that telnet
connects to is available after the listen
.
In all [your] cases, telnet
sees a connection established.
When you do ev.events = 0;
, the epoll_wait
will wait forever.
When you do ev.events = EPOLLIN
, the epoll_wait
will return. But, since you have nothing after that, main
returns and the socket is closed when the server terminates. That is what telnet
sees (e.g. Connection closed by foreign host.
)
If you do:
printf("running ...\n");
while (1)
sleep(1);
after the epoll_wait
, then telnet
will see the same effect, regardless of the value of ev.events