Unix : Epoll, catch ctrl+d and ctrl+c in server

核能气质少年 提交于 2019-12-12 01:31:26

问题


I use epoll to build a server, this is the code where I init epoll :

core->fd_epoll = epoll_create(LIMIT_CLIENT);
ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
ev.data.fd = core->socket_main;
epoll_ctl(core->fd_epoll, EPOLL_CTL_ADD, core->socket_main, &ev);
while (1)
{
  nfds = epoll_wait(core->fd_epoll, &ev, 90000, -1);
  ...
}

And when I use it to check if there's something new on my fds :

for (i = 0; i < nfds; i++)
{
  fd = ev[i].data.fd;
  if (fd == core->socket_main)
    {
      socket_fils = socket_accept(core->socket_main, 0);
      event.data.fd = socket_fils;
      event.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
      xepoll_ctl(core->fd_epoll, EPOLL_CTL_ADD, socket_fils, &event);
      printf("Incoming => FD fils %d\n", socket_fils);
    }
  else
    printf("Event %x\n", ev[i].events);
}

When I use netcat to send a message to the server the bitfield events is equal to 1 (EPOLLIN) When I send a ctrl+c, netcat quits and my bitfield is equal to 2001 (EPOLLIN and EPOLLRDHUP) When I send a ctrl+d, netcat doesn't quit but my bitfield is equal to 2001 too...

After a ctrl+d, my server closes the socket. It's not normal... A ctrl+d should'nt close the socket and return a different bitfield.

How can I know, in the server, if it's ctrl+c or ctrl+d ?

Thank you.


回答1:


ctrl+c and ctrl+d keypresses on the terminal that is running netcat cannot be "seen" directly by your server. They cause, respectively, a SIGINT signal to be sent to netcat, and an EOF condition to be seen by netcat on its stdin. What netcat does with that is really up to netcat, not up to your server. Here's what they do for me:

  • ctrl+c which sends SIGINT to netcat: netcat is killed because that is the default action of SIGINT, and netcat doesn't change it. When netcat dies the socket is automatically closed. The server senses this as available incoming data, consistent with the EPOLLIN|EPOLLRDHUP condition you are seeing. If you read the socket, you will find that an EOF is waiting for you.

  • ctrl+d which sends an EOF on netcat's stdin: netcat noticed the EOF. It will send no further data through the socket. However, it continues running and reading from the socket in case the server has more data to send.

In other words, I can't reproduce the netcat behaviour you are seeing (with Linux 2.6 and netcat v1.10-38). Perhaps your version of netcat shuts down the socket for writing after reading an EOF on stdin?



来源:https://stackoverflow.com/questions/10981790/unix-epoll-catch-ctrld-and-ctrlc-in-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!