2

if I add an event for a specific socket to event loop, for example, a TCP connection socket. then it may happen that the socket is closed, then how will libevent act? can it detect this?

thanks!

misteryes
  • 2,167
  • 4
  • 32
  • 58
  • Your title and your question don't agree. The answer to your title is that it doesn't detect closure by the peer, it just detects a read event. – user207421 May 25 '13 at 00:03

1 Answers1

0

EDIT: I think I misinterpreted your question at first.

If you mean that the socket is closed from the remote end

As per the documentation you can use the event_new() and event_add() calls to register interest in a socket. Make sure you specify EV_READ since you are interested in when the socket is closed.

Remember that there is no difference in file descriptor readiness between data available for reading and a closed socket. Normally you must read the socket to find out which condition is true, but if you don't want to read the socket then you can look here for a hint.

If you mean that the socket is locally closed (the file descriptor was closed

Using a file descriptor after it has been closed is never defined and can always lead to undefined results. This is not specific to libevent. Before you close a file descriptor, you must make sure that no other thread in your program is using it, and you must make sure that no other part of your program is going to try using it in the future. That means unregistering the file descriptor from libevent at the same time that you close it.

Community
  • 1
  • 1
Celada
  • 21,627
  • 4
  • 64
  • 78
  • so how to check whether socket is closed or not? – misteryes May 23 '13 at 10:24
  • I'm sorry, I misinterpreted your question. You mean that the local end of the socket (the local file descriptor) is closed, right? If so, I will write a different answer, but it boils down to "never do that". – Celada May 23 '13 at 14:08
  • OK, can you explain both cases: 1 the local socket is closed 2 the remote socket is closed. Thanks! – misteryes May 23 '13 at 15:03
  • I think for the first case, I should check the return value, `n=recv(fd,...)` if n = 0, it means the remote socket send FIN/ACK , if n=-1, it may be a RST packet or not data – misteryes May 23 '13 at 16:24